该功能旨在用STRING B替换所有出现的STRING A
但是如果STRING A只是一个字符,那该怎么办呢。
使用此功能会是浪费资源吗?
或者修改它会更合乎逻辑吗?
如果是这样......怎么样。
char *replaceWord(const char *s, const char *oldW,
const char *newW)
{
char *result;
int i, cnt = 0;
int newWlen = strlen(newW);
int oldWlen = strlen(oldW);
// Counting the number of times old word
// occur in the string
for (i = 0; s[i] != '\0'; i++)
{
if (strstr(&s[i], oldW) == &s[i])
{
cnt++;
// Jumping to index after the old word.
i += oldWlen - 1;
}
}
// Making new string of enough length
result = (char *)malloc(i + cnt * (newWlen - oldWlen) + 1);
i = 0;
while (*s)
{
// compare the substring with the result
if (strstr(s, oldW) == s)
{
strcpy(&result[i], newW);
i += newWlen;
s += oldWlen;
}
else
result[i++] = *s++;
}
result[i] = '\0';
return result;
}
使用示例:
char str[] = "xxforxx";
char c[] = "xx";
char d[] = "TEST";
char *result = NULL;
result = replaceWord(str, c, d);