c语言strstr函数的用法
时间: 2023-10-03 09:08:34 浏览: 105
C语言中的strstr函数用于在一个字符串中查找指定的子字符串,并返回其在原字符串中的位置。其函数原型如下:
```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 *subStr = "world";
char *result = strstr(str, subStr);
if (result != NULL)
{
printf("子字符串在原字符串中的位置为:%d\n", result - str);
}
else
{
printf("未找到子字符串!\n");
}
return 0;
}
```
输出结果为:
```
子字符串在原字符串中的位置为: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。