c语言查找字符串并替换
时间: 2024-01-31 13:02:16 浏览: 37
在C语言中,你可以使用标准库函数`strstr`来查找字符串,并使用`strcpy`函数来替换字符串。下面是一个示例代码:
```c
#include <stdio.h>
#include <string.h>
void replaceString(char *str, const char *search, const char *replace) {
char *pos, temp[1000];
int lenSearch = strlen(search);
int lenReplace = strlen(replace);
while ((pos = strstr(str, search)) != NULL) {
strcpy(temp, str);
int index = pos - str;
strcpy(str + index, replace);
strcpy(str + index + lenReplace, temp + index + lenSearch);
}
}
int main() {
char str[1000] = "Hello, world! This is a test string.";
const char search[] = "test";
const char replace[] = "example";
replaceString(str, search, replace);
printf("Modified string: %s\n", str);
return 0;
}
```
在上面的示例中,`replaceString`函数接受一个字符串`str`、要搜索的子字符串`search`和要替换的字符串`replace`作为参数。它使用`strstr`函数找到第一个匹配的子字符串,并使用`strcpy`函数进行替换。然后,它继续搜索并替换所有匹配的子字符串,直到没有匹配项为止。
运行上述代码,输出将是:`Modified string: Hello, world! This is a example string.`。这里将字符串中的"test"替换为"example"。