C语言中如何用一个字符串替换一个主串中的子串

2024-12-04 18:57:28
推荐回答(1个)
回答1:

参考以下代码
#include
//oldstr原字符串, newstr新字符串, oldsubstr原字符串中要替换的子串, newsubstr新字符串中替换后的新子串
void replace(char *oldstr, char *newstr, char *oldsubstr, char *newsubstr)
{
int i, j;
int nLen = strlen(oldstr);
int nLenSub = strlen(oldsubstr);
for(i=0, j=0; i {
if(0 == strncmp(oldstr+i, oldsubstr, nLenSub))
{
strcat(newstr+j, newsubstr);
j += strlen(newsubstr);
i += nLenSub;
}
else
{
newstr[j++] = oldstr[i++];
}
}
}