strstr函数用法举例
时间: 2024-04-19 21:21:21 浏览: 24
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。
相关问题
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."
c++里strstr函数用法
`strstr`函数是C++标准库中的一个字符串函数,其使用方法如下:
```c++
const char *strstr(const char *str1, const char *str2);
```
该函数在字符串`str1`中查找第一次出现字符串`str2`的位置,如果找到,则返回该位置的指针;如果未找到,则返回`nullptr`。
示例代码:
```c++
#include <iostream>
#include <cstring>
int main() {
const char* str1 = "hello, world!";
const char* str2 = "world";
const char* result = strstr(str1, str2);
if (result) {
std::cout << "Found at position " << result - str1 << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
return 0;
}
```
输出结果为:
```
Found at position 7
```
需要注意的是,`strstr`函数是区分大小写的,如果需要进行不区分大小写的字符串查找,可以使用`strcasestr`函数。