使用C语言查找替换字符串
时间: 2023-07-20 12:11:19 浏览: 72
可以使用C语言中的字符串函数实现字符串的查找和替换。
1. 查找字符串
可以使用strstr函数来查找字符串中是否包含指定的子字符串。该函数的原型如下:
```c
char* strstr(const char* str1, const char* str2);
```
其中,str1是要查找的字符串,str2是要查找的子字符串。如果str2存在于str1中,则返回str2在str1中第一次出现的位置的指针;否则返回NULL。
例如,以下代码演示了如何查找字符串中是否包含指定的子字符串:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello, world!";
char str2[] = "world";
char* p = strstr(str1, str2);
if (p != NULL) {
printf("'%s' is found in '%s' at position %ld.\n", str2, str1, p - str1);
} else {
printf("'%s' is not found in '%s'.\n", str2, str1);
}
return 0;
}
```
输出结果为:
```
'world' is found in 'Hello, world!' at position 7.
```
2. 替换字符串
可以使用strcpy和strcat函数来实现字符串的替换。具体步骤如下:
- 先将原字符串的前缀复制到一个新的字符串中;
- 然后将要替换的字符串复制到新的字符串中;
- 最后将原字符串的后缀复制到新的字符串中。
例如,以下代码演示了如何将字符串中的指定子字符串替换为新的字符串:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello, world!";
char str2[] = "world";
char str3[] = "everyone";
char* p = strstr(str1, str2);
if (p != NULL) {
char new_str[100] = {0};
strncpy(new_str, str1, p - str1);
strcat(new_str, str3);
strcat(new_str, p + strlen(str2));
printf("'%s' is replaced to '%s'.\n", str2, str3);
printf("Old string: %s\n", str1);
printf("New string: %s\n", new_str);
} else {
printf("'%s' is not found in '%s'.\n", str2, str1);
}
return 0;
}
```
输出结果为:
```
'world' is replaced to 'everyone'.
Old string: Hello, world!
New string: Hello, everyone!
```