C语言编程,将字符串中的子串替换成另一字符串
时间: 2023-10-02 19:06:52 浏览: 192
可以使用C语言中的字符串函数和循环来实现字符串中子串的替换。具体步骤如下:
1. 定义原字符串和要替换的子串和目标字符串。
```c
char str[] = "hello, world!";
char substr[] = "world";
char targetstr[] = "ChitChat";
```
2. 使用一个循环,查找原字符串中的子串并替换成目标字符串。
```c
char *pos = NULL;
while ((pos = strstr(str, substr)) != NULL) {
int len1 = strlen(str);
int len2 = strlen(targetstr);
int len3 = strlen(substr);
char *temp = (char*)malloc(sizeof(char) * (len1 - len3 + len2 + 1));
strncpy(temp, str, pos - str);
temp[pos - str] = '\0';
strcat(temp, targetstr);
strcat(temp, pos + len3);
strcpy(str, temp);
free(temp);
}
```
3. 最后输出替换后的字符串。
```c
printf("%s\n", str);
```
完整的代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char str[] = "hello, world!";
char substr[] = "world";
char targetstr[] = "ChitChat";
char *pos = NULL;
while ((pos = strstr(str, substr)) != NULL) {
int len1 = strlen(str);
int len2 = strlen(targetstr);
int len3 = strlen(substr);
char *temp = (char*)malloc(sizeof(char) * (len1 - len3 + len2 + 1));
strncpy(temp, str, pos - str);
temp[pos - str] = '\0';
strcat(temp, targetstr);
strcat(temp, pos + len3);
strcpy(str, temp);
free(temp);
}
printf("%s\n", str);
return 0;
}
```