C语言编程字符串的替换
时间: 2023-09-23 09:12:27 浏览: 92
可以使用字符串函数strreplace()函数来实现C语言编程中的字符串替换。该函数需要输入三个参数,分别为要替换的原字符串、要搜索的子字符串和替换子字符串,示例代码如下:
```
#include <string.h>
char* str_replace(char* original, const char* pattern, const char* new_word)
{
int len1,len2,len3,i,j,k;
char* result;
len1 = strlen(original);
len2 = strlen(pattern);
len3 = strlen(new_word);
if (len2 == 0) return original;
result = (char*)malloc(sizeof(char)*(len1 + 1));
for (i = 0, j = 0; i < len1;)
{
if (original[i] == pattern[j])
{
for (k = 0; pattern[j] != '\0' && original[i] == pattern[j]; i++, j++, k++);
if (pattern[j] == '\0')
{
for (k = 0; k < len3; k++)
result[i - len2 + k] = new_word[k];
j = 0;
}
else
{
result[i] = original[i];
j = 0;
i++;
}
}
else
{
result[i] = original[i];
j = 0;
i++;
}
}
result[len1] = '\0';
free(original);
return result;
}
```
这样,你就可以通过str_replace()函数实现字符串替换了。
阅读全文