strstr(s1,s2)
时间: 2023-10-08 22:09:04 浏览: 48
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
```
相关问题
strstr(s1, s2);
The function strstr(s1, s2) searches for the first occurrence of the substring s2 in the string s1. If the substring is found, it returns a pointer to the beginning of the substring in s1. If the substring is not found, it returns a null pointer.
For example, if we have the following code:
```
char str1[] = "Hello world";
char str2[] = "world";
char *result;
result = strstr(str1, str2);
if (result) {
printf("Substring found at position %d\n", result - str1);
} else {
printf("Substring not found\n");
}
```
The output will be "Substring found at position 6", because the substring "world" is found in the string "Hello world" starting at position 6.
strstr(s1, s2);例子
假设我们有两个字符串s1和s2:
```c++
char s1[] = "Hello World!";
char s2[] = "World";
```
我们想要查找s1中是否包含s2,我们可以使用函数`strstr()`来实现:
```c++
char* result = strstr(s1, s2);
```
该函数将返回一个指向s1中第一次出现s2的位置的指针,如果s1中不包含s2,则返回`NULL`。
在上面的例子中,result将指向字符串s1中的"World"。
完整的代码如下所示:
```c++
#include <iostream>
#include <cstring>
int main() {
char s1[] = "Hello World!";
char s2[] = "World";
char* result = strstr(s1, s2);
if (result != NULL) {
std::cout << "s2 is found in s1 at position " << result - s1 << std::endl;
} else {
std::cout << "s2 is not found in s1" << std::endl;
}
return 0;
}
```
输出结果为:
```
s2 is found in s1 at position 6
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)