下面再来看看strstr()函数
功 能:在串中查找指定字符串的第一次出现
用 法: char *strstr(char *str1, char *str2);
strstr原型:extern char *strstr(char *haystack, char *needle);
用法:#include <string.h>
功能:从字符串haystack中寻找needle第一次出现的位置(不比较结束符NULL)。
说明:返回指向第一次出现needle位置的指针,如果没找到则返回NULL。
当然和上一个函数一样输出的的从查找的字符串开始后面所有的字符(查找的字符也包含)
举例
//strstr.c
#include<syslib.h>
#include<string.h>
main()
{
char*s="Golden Global View";
char*l="lob";
char*p;
clrscr();
p=strstr(s,l);
if(p)
printf("%s",p);
else
printf("NotFound!");
getchar();
return0;
}
语法:* strstr(str1,str2)
str1:被查找目标 string expression to search.
str2:要查找对象 The string expression to find.
该函数返回str2第一次在str1中的位置,如果没有找到,返回NULL
Thestrstr() function returns the ordinal
positionwithin str1 of the first occurrence of str2. If str2 is not
foundin str1, strstr() returns 0.
例子:
功能:从字串” string1 onexxx string2 oneyyy”中寻找”yyy”
(假设xxx和yyy都是一个未知的字串)
char*s=” string1 onexxx string2 oneyyy”;
char*p;
p=strstr(s,”string2”);
if(!p)printf(“Not Found!”);
p=strstr(p,”one”);
if(!p)printf(“Not Found!”);
p+=strlen(“one”)
printf(“%s”,p);
说明:如果直接写语句p=strstr(s,”one”),则找到的是onexxx string2 oneyyy,不符合要求
所以需采用二次查找法找到目标
下面是一个实现此函数的程序
- include <iostream>
- #include <cassert>
- using namespace std;
- const char* StrStr(const char *str1, const char *str2)
- {
- assert(NULL != str1 && NULL != str2);
- while(*str1 != '\0')
- {
- const char *p = str1;
- const char *q = str2;
- const char *res = NULL;
- if(*p == *q)
- {
- res = p;
- while(*p && *q && *p++ == *q++)
- ;
- if(*q == '\0')
- return res;
- }
- str1++;
- }
- return NULL;
- }
- int main()
- {
- const char *str1 = "wangyang";
- const char *str2 = "ang";
- const char *res = StrStr(str1, str2);
- if(res != NULL)
- cout<<res<<endl;
- else
- cout<<"NOT"<<endl;
- system("pause");
- }