c语言strstr函数的用法
时间: 2023-05-08 16:55:41 浏览: 125
C语言的strstr函数是用于查找一个字符串中是否包含另一个子字符串的函数。其使用方法如下:
函数声明:char *strstr(const char *str1, const char *str2);
函数参数:str1表示要查找的字符串,str2表示要查找的子字符串。
函数返回值:如果找到了子字符串,则返回子字符串在原字符串中的指针;如果没有找到,则返回NULL。
函数用法:
使用前需要包含头文件<string.h>。
该函数会在str1字符串中查找第一次出现的str2子字符串,不包括匹配到的字符。
如果找到了子字符串,则返回其在原字符串中的指针;如果没有找到,则返回NULL。
如果str2是空字符串,则返回str1。
该函数区分大小写。
例如:
char str1[]="hello, world";
char str2[]="world";
char *ptr;
ptr=strstr(str1, str2); //查找str1中是否有str2
if(ptr!=NULL) //如果找到了
printf("Found at position:%d\n", ptr-str1+1);
else
printf("Not found\n");
以上代码中,首先定义了两个字符串str1和str2,然后使用strstr函数在str1中查找str2子字符串。如果找到了,则输出其在原字符串中的位置;如果没有找到,则输出“Not found”。
相关问题
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。