如何替换字符串在C? [英] how to replace substring in c?
问题描述
本示例工作,但我认为内存泄漏。简单的Web服务器模块中使用的功能,如果你使用此功能从而共享内存增长。
This example works but I think that the memory leaks. Function used in the simple web server module and thus shared memory grows if you use this function.
char *str_replace ( const char *string, const char *substr, const char *replacement ){
char *tok = NULL;
char *newstr = NULL;
char *oldstr = NULL;
if ( substr == NULL || replacement == NULL ) return strdup (string);
newstr = strdup (string);
while ( (tok = strstr ( newstr, substr ))){
oldstr = newstr;
newstr = malloc ( strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) + 1 );
memset(newstr,0,strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) + 1);
if ( newstr == NULL ){
free (oldstr);
return NULL;
}
memcpy ( newstr, oldstr, tok - oldstr );
memcpy ( newstr + (tok - oldstr), replacement, strlen ( replacement ) );
memcpy ( newstr + (tok - oldstr) + strlen( replacement ), tok + strlen ( substr ), strlen ( oldstr ) - strlen ( substr ) - ( tok - oldstr ) );
memset ( newstr + strlen ( oldstr ) - strlen ( substr ) + strlen ( replacement ) , 0, 1 );
free (oldstr);
}
return newstr;
}
推荐答案
有一个问题,我可以看到的是,如果替换字符串包含搜索字符串,你永远循环下去(直到耗尽内存)。
One problem I can see is that if the replacement string contains the search string, you'll loop forever (until you run out of memory).
例如:
char *result = str_replace("abc", "a", "aa");
此外,每更换一个实例的时间做其他的malloc / free是pretty昂贵。
Also, doing another malloc/free every time you replace one instance is pretty expensive.
有一个更好的办法是在输入字符串做的正是通过2次:
A better approach would be to do exactly 2 passes over the input string:
-
第一遍,算上搜索字符串的许多情况下是如何present
the first pass, count how many instances of the search string are present
现在你知道很多比赛怎么样,你的计算结果与放大器的长度;曾经的malloc:
now that you know how many matches, compute the length of your result & malloc once:
的strlen(字符串)+匹配*(strlen的(替代)-strlen(SUBSTR))+ 1
strlen(string) + matches*(strlen(replacement)-strlen(substr)) + 1
进行第二次通过源字符串,复制/替换
make a second pass through the source string, copying/replacing
这篇关于如何替换字符串在C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!