strstr(s1, s2);用法
时间: 2023-11-26 20:06:30 浏览: 43
strstr(s1, s2)函数用于在字符串s1中查找子串s2的第一次出现位置,并返回该位置的指针。如果s2不是s1的子串,则返回NULL。
例如,以下代码将在字符串s1中查找子串s2:
```c
char s1[] = "hello world";
char s2[] = "world";
char *ptr = strstr(s1, s2);
```
在上述代码中,ptr指向字符串s1中子串s2的第一次出现位置。如果s2不是s1的子串,则ptr为NULL。
相关问题
strstr(s1,s2)
strstr(s1, s2)是一个C语言中的字符串处理函数,用于查找字符串s2在字符串s1中第一次出现的位置(即s2在s1中的子串)。函数返回一个指向第一次出现的位置的指针,如果没有找到匹配的子串,则返回NULL。
示例用法:
```c
#include <stdio.h>
#include <string.h>
int main() {
char s1[] = "Hello, World!";
char s2[] = "World";
char* ptr = strstr(s1, s2);
if (ptr != NULL) {
printf("'%s' is found in '%s'\n", s2, s1);
printf("Position: %ld\n", ptr - s1);
} else {
printf("'%s' is not found in '%s'\n", s2, s1);
}
return 0;
}
```
输出结果:
```
'World' is found in 'Hello, World!'
Position: 7
```
用s2替换str中的s1,s1和s2都是字符串,长度可能不相等,用指针的方法
好的,如果您想用指针的方法来实现字符串替换,可以使用 C 风格字符串的指针和循环结合起来实现。具体步骤如下:
1. 包含头文件 #include <cstring>
2. 创建一个字符串,存储待替换的字符串。
```
char str[] = "this is a test string";
char s1[] = "test";
char s2[] = "replace";
```
3. 使用 strstr 函数查找 s1 的位置。
```
char* pos = strstr(str, s1);
```
如果 s1 存在于 str 中,pos 就是 s1 在 str 中的位置;否则 pos 就是 NULL。
4. 使用循环和 strcpy 函数来实现替换。
```
while (pos != NULL) {
strcpy(pos, s2);
pos = strstr(pos + strlen(s2), s1);
}
```
以上代码的含义是:如果 s1 存在于 str 中,则从字符串的 pos 位置开始,使用 strcpy 函数将 s2 替换为 s1。并更新 pos 的值为下一个 s1 出现的位置。
5. 最终得到的字符串即为替换后的结果。
```
cout << str << endl;
```
输出结果为:"this is a replace string" 中的 "test" 被替换为了 "replace"。
希望这些步骤能够帮助您进行字符串替换。