strstr(C語言函式)

本詞條是多義詞,共2個義項
更多義項 ▼ 收起列表 ▲
函式實現,套用舉例,
包含檔案:string.h
函式名: strstr
函式原型:
extern char *strstr(char *str1, const char *str2);
語法:
* strstr(str1,str2)
str1: 被查找目標 string expression to search.
str2: 要查找對象 The string expression to find.
返回值:若str2是str1的子串,則返回str2在str1的首次出現的地址;如果str2不是str1的子串,則返回NULL。
例子:
char str[]="1234xyz";char *str1=strstr(str,"34");cout << str1 << endl;
顯示的是: 34xyz

函式實現

1.Copyright 1990 Software Development Systems, Inc.
char *strstr(const char *s1,const char *s2){ int len2; if(!(len2=strlen(s2)))//此種情況下s2不能指向空,否則strlen無法測出長度,這條語句錯誤     return(char*)s1; for(;*s1;++s1) {     if(*s1==*s2 && strncmp(s1,s2,len2)==0)     return(char*)s1; } return NULL;}
2.Copyright 1986 - 1999 IAR Systems. All rights reserved
char *strstr(constchar*s1,constchar*s2){    int n;    if(*s2)    {        while(*s1)        {            for(n=0;*(s1+n)==*(s2+n);n++)            {                if(!*(s2+n+1))                    return(char*)s1;            }            s1++;        }        return NULL;    }    else        return (char*)s1;}
3. GCC-4.8.0
char *strstr(const char *s1,const char *s2){    const char *p=s1;    const size_tlen=strlen(s2);    for(;(p=strchr(p,*s2))!=0;p++)    {        if(strncmp(p,s2,size_tlen)==0)            return (char*)p;    }    return(0);}
4. 常用經典實現方法
char *strstr(const char *str1, const char *str2){    char *cp = (char*)str1;    char *s1, *s2;    if (!*str2)        return((char *)str1);    while (*cp)    {        s1 = cp;        s2 = (char *)str2;        while (*s1 && *s2 && !(*s1 - *s2))            s1++, s2++;        if (!*s2)            return(cp);        cp++;    }    return(NULL);}
4的補充char * strstr ( char *buf, char *sub){    if(!*sub)   return buf;    char *bp, *sp;    while (*buf)    {   bp = buf;   sp = sub;   do   {  if(!*sp) return buf;   } while (*bp++ == *sp++);   buf++;    }    return 0;}

套用舉例

// strstr.c
#include <stdio.h>#include <string.h>main(){    char *s="GoldenGlobalView";    char *l="lob";    char *p;        p=strstr(s,l);    if(p)        printf("%s",p);    else        printf("NotFound!");    return 0;}
//功能:從字串” string1 onexxx string2 oneyyy”中尋找”yyy”
(假設xxx和yyy都是一個未知的字串)
char *s=”string1onexxxstring2oneyyy”;char *p;p=strstr(s,”yyy”);if(p!=NULL)    printf(“%s”,p);else    printf("notfound\n");
說明:如果直接寫語句p=strstr(s,”one”),找到的是onexxxstring2oneyyy
char *mystrstr(char*s1,char*s2){    if(*s1==0)    {        if(*s2)            return (char*)NULL;        return (char*)s1;    }    while(*s1)    {        int i=0;        while(1)        {            if(s2[i]==0)                return s1;            if(s2[i]!=s1[i])                break;            i++;        }        s1++;    }    return (char*)NULL;}

相關詞條

熱門詞條

聯絡我們