strstr函数的用法
时间: 2023-09-07 07:13:43 浏览: 68
strstr函数是C语言中的一个库函数,其作用是在一个字符串中查找另一个字符串的第一次出现。该函数的原型如下:
```c
char *strstr(const char *haystack, const char *needle);
```
其中haystack表示要查找的字符串,needle表示要查找的子字符串。该函数返回一个指向needle第一次出现的位置的指针,若找不到,则返回NULL。
例如:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "hello world";
char *ptr = strstr(str, "world");
if(ptr != NULL)
{
printf("找到了字符串 world,位置为:%d\n", ptr-str);
}
else
{
printf("没有找到字符串 world\n");
}
return 0;
}
```
输出结果为:
```
找到了字符串 world,位置为:6
```
说明在字符串"hello world"中找到了子字符串"world",并且它的位置是从索引6开始的。
相关问题
strstr函数使用方法
strstr函数是C语言中的一个字符串处理函数,其作用是在一个字符串中查找另一个字符串第一次出现的位置。其函数原型为:
```
char *strstr(const char *str1, const char *str2);
```
其中,str1表示要被查找的字符串,str2表示要查找的子字符串。函数返回值为一个指向str2在str1中第一次出现位置的指针,如果str2未在str1中出现,则返回NULL。
使用该函数时,需要注意以下几点:
1. 在使用该函数前,需要确保str1和str2指向的字符串以'\0'结尾,否则可能会导致结果不正确。
2. 在使用该函数时,应该判断函数的返回值是否为NULL,以确保查找到了需要的子字符串。
下面是一个使用strstr函数的例子:
```
#include <stdio.h>
#include <string.h>
int main()
{
char str1[] = "hello world";
char str2[] = "world";
char *p = NULL;
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 6."
strstr函数用法举例
strstr函数是C语言中的字符串处理函数,用于在一个字符串中查找指定子串的位置。它的函数原型如下:
```c
char *strstr(const char *haystack, const char *needle);
```
其中,`haystack`是要搜索的字符串,`needle`是要查找的子串。函数返回子串在字符串中第一次出现的位置,如果找不到则返回NULL。
下面是一个使用strstr函数的例子:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, world!";
char *result = strstr(str, "world");
if (result != NULL) {
printf("子串在字符串中的位置:%ld\n", result - str);
} else {
printf("未找到子串\n");
}
return 0;
}
```
输出结果为:
```
子串在字符串中的位置:7
```
这个例子中,我们在字符串"Hello, world!"中查找子串"world",并输出子串在字符串中的位置。由于子串在字符串中的起始位置是从0开始计数的,所以输出结果为7。