strstr查找函数
时间: 2023-12-26 14:25:52 浏览: 38
strstr函数是C语言中的字符串查找函数,用于在一个字符串中查找另一个字符串的出现位置。该函数的函数结构为:char *strstr(const char*str1,const char*str2)。其中str1为要查找的字符串,str2为要查找的子字符串。如果找到了子字符串,则返回子字符串在原字符串中的地址;如果没有找到,则返回NULL。
下面是一个示例代码,演示了如何使用strstr函数查找字符串中的子字符串:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100] = "hello world";
char str2[20] = "world";
char *result = NULL;
result = strstr(str1, str2);
if (result == NULL)
{
printf("Not found\n");
}
else
{
printf("Substring found at index %ld\n", result - str1);
}
return 0;
}
```
上述代码中,我们首先定义了两个字符串str1和str2,然后使用strstr函数在str1中查找str2。如果找到了str2,则输出子字符串在原字符串中的位置;否则输出"Not found"。
相关问题
模拟strstr函数查找子串
可以使用循环逐一比较子串和字符串中的每个字符,如果匹配成功,则返回当前位置,否则继续往后查找,直到字符串末尾。
以下是一个示例代码:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int strStr(char *haystack, char *needle) {
if (*needle == '\0') return 0;
int len1 = strlen(haystack);
int len2 = strlen(needle);
for (int i = 0; i < len1 - len2 + 1; i++) {
int j = 0;
for (; j < len2; j++) {
if (haystack[i + j] != needle[j]) {
break;
}
}
if (j == len2) {
return i;
}
}
return -1;
}
int main() {
char s1[] = "hello world";
char s2[] = "world";
int pos = strStr(s1, s2);
cout << pos << endl; // 6
return 0;
}
```
在上面的代码中,我们首先判断 needle 是否为空串,如果是,则直接返回 0,因为空串是任何字符串的子串。接着,我们使用两个变量 len1 和 len2 分别记录字符串 haystack 和 needle 的长度。然后,我们从字符串 haystack 的第一个字符开始,逐一比较 haystack 和 needle 中的字符,如果匹配成功,则返回当前位置 i,否则继续往后查找,直到字符串末尾。如果找不到,则返回 -1。
strstr的函数原型
strstr函数的函数原型是:
```c++
const char * strstr ( const char * str1, const char * str2 );
```
这个函数用于在字符串str1中查找是否包含字符串str2,并返回第一次出现的位置。如果找到了str2,则返回指向str1中第一次出现str2的指针;如果没有找到,则返回空指针。这个函数是C++中用于子字符串查找的重要工具[^2]。