是否有一种实用的方法可以在以下字符串中用%
替换所有出现的%%
char * str = "%s %s %s";
printf("%s",str);
所以结果是:
%%s %%s %%s
或者我必须使用扫描字符串中每个字符的函数,直到找到%
,然后将其替换为%%
?
答案 0 :(得分:0)
您应该理解,无法在同一str
中进行替换,因为增加字符数将需要更多内存。所以在更换次数之前必须计算更换次数。
以下函数允许将单个字符替换为字符串(字符集)。
char *replace(const char *s, char ch, const char *repl) {
// counting the number of future replacements
int count = 0;
const char *t;
for(t=s; *t; t++)
{
count += (*t == ch);
}
// allocation the memory for resulting string
size_t rlen = strlen(repl);
char *res = malloc(strlen(s) + (rlen-1)*count + 1);
if(!res)
{
return 0;
}
char *ptr = res;
// making new string with replacements
for(t=s; *t; t++) {
if(*t == ch) {
memcpy(ptr, repl, rlen); // past sub-string
ptr += rlen; // and shift pointer
} else {
*ptr++ = *t; // just copy the next character
}
}
*ptr = 0;
// providing the result (memory allocated in this function
// should be released outside this function with free(void*) )
return res;
}
对于您的特定任务,此功能可用作
char * str = "%s %s %s";
char * newstr = replace(str, '%', "%%");
if( newstr )
printf("%s",newstr);
else
printf ("Problems with making string!\n");
注意,新的字符串存储在堆中(根据初始字符串的大小和替换次数分配的动态内存),因此当不再需要newstr
时,应该重新分配内存程序超出了newstr
指针的范围。
想想
的地方if( newstr )
{
free(newstr);
newstr = 0;
}