下面再來看看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");
- }