是那里与%%
取代的%
所有出现在下面的字符串的实用方法用%%?替换所有%的出现,需要一个函数吗?
char * str = "%s %s %s";
printf("%s",str);
所以结果是:
%%s %%s %%s
,或者必须我使用其中扫描每个字在一个功能该字符串直到找到%
,然后用%%
替换它?
是那里与%%
取代的%
所有出现在下面的字符串的实用方法用%%?替换所有%的出现,需要一个函数吗?
char * str = "%s %s %s";
printf("%s",str);
所以结果是:
%%s %%s %%s
,或者必须我使用其中扫描每个字在一个功能该字符串直到找到%
,然后用%%
替换它?
您应该明白,不能在同一个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;
}
有一个在标准库中没有这样的功能,所以,是的,你必须写你自己的。 –
首先,由于字符串文字不能被改变,所以有必要分配一个允许数组或者分配另一个数组。 – BLUEPIXY
可能重复[什么是替换C中的字符串?](https://stackoverflow.com/questions/779875/what-is-the-function-to-replace-string-in-c) – phd