strstr函数的用法
时间: 2023-09-26 18:06:58 浏览: 61
strstr函数是C语言中字符串处理函数之一,用于在一个字符串中查找另一个字符串的第一次出现位置,函数原型如下:
```c
char* strstr(const char* str1, const char* str2);
```
其中,str1是要查找的字符串,str2是要查找的子字符串。函数返回str2在str1中第一次出现的位置的指针,若未找到则返回NULL。
例如,以下代码演示了如何使用strstr函数查找一个字符串中是否包含另一个字符串:
```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("The substring \"%s\" is found in \"%s\" at position %ld.\n", str2, str1, p - str1);
}
else
{
printf("The substring \"%s\" is not found in \"%s\".\n", str2, str1);
}
return 0;
}
```
输出结果为:
```
The substring "world" is found in "hello world" at position 6.
```
上述代码中,我们首先定义了两个字符串str1和str2,然后使用strstr函数查找str2在str1中第一次出现的位置,最后输出查找结果。