strstr
strstr(str1,str2) 函数⽤于判断字符串str2是否是str1的⼦串。如果是,则该函数返回str2在str1中⾸次出现的地址;否则,返回NULL。
C语⾔函数
包含⽂件:函数名: strstr函数原型:
1extern char *strstr(char *str1, const char *str2);语法:
1* strstr(str1,str2)
str1: 被查找⽬标 string expression to search.str2: 要查找对象 The string expression to find.
返回值:若str2是str1的⼦串,则返回str2在str1的⾸次出现的地址;如果str2不是str1的⼦串,则返回NULL。例⼦:
1char str[]=\"1234xyz\";2char *str1=strstr(str,\"34\");3cout << str1 << endl;显⽰的是: 34xyz
函数实现
1.Copyright 1990 Software Development Systems, Inc.1
2char *strstr(const char *s1,const char *s2)3{
4 int len2;
if(!(len2=strlen(s2)))//此种情况下s2不能指向空,否则strlen⽆法测出长度,这条语句错误5 return(char*)s1;6 for(;*s1;++s1)7 {
8 if(*s1==*s2 && strncmp(s1,s2,len2)==0) return(char*)s1;9 }
10 return NULL;11}12
2.Copyright 1986 - 1999 IAR Systems. All rights reserved12
3char *strstr(constchar*s1,constchar*s2)4{
5 int n; if(*s2)6 {
7 while(*s1)8 {
9 for(n=0;*(s1+n)==*(s2+n);n++) {
10 if(!*(s2+n+1))
11 return(char*)s1;12 }
13 s1++; }14
return NULL;15 }16 else
17 return (char*)s1;18}19
3. GCC-4.8.01
2char *strstr(const char*s1,const char*s2)
{
2{3
const char*p=s1;4
const size_tlen=strlen(s2);5 for(;(p=strchr(p,*s2))!=0;p++)6 {
7 if(strncmp(p,s2,len)==0)8 return (char*)p;9 }
return(0);10}11
应⽤举例
// strstr.c1
2#include char *s=\"GoldenGlobalView\";6 char *l=\"lob\";7 char *p;8 clrscr(); 9 p=strstr(s,l);10 if(p) 11 printf(\"%s\ else 12 printf(\"NotFound!\");13 getchar();14 return0;15}16 //功能:从字串” string1 onexxx string2 oneyyy”中寻找”yyy”(假设xxx和yyy都是⼀个未知的字串)1 char *s=”string1onexxxstring2oneyyy”;2 char *p; 3p=strstr(s,”yyy”);4if(p!=NULL) 5 printf(“%s”,p);6else printf(\"notfound\\n\");7 说明:如果直接写语句p=strstr(s,”one”),找到的是onexxxstring2oneyyy12 char *mystrstr(char*s1,char*s2)3{ 4 if(*s1==0)5 { 6 if(*s2) 7 return (char*)NULL;8 return (char*)s1; } 9 while(*s1)10 { 11 int i=0;12 while(1)13 { 14 if(s2[i]==0) return s1;15 if(s2[i]!=s1[i])16 break;17 i++; } 18 s1++;19 } 20 return (char*)NULL;21}2223 因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- sceh.cn 版权所有 湘ICP备2023017654号-4
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务