strstr
(C语言函数)
编辑
锁定
讨论
上传视频
本词条缺少概述图,补充相关内容使词条更完整,还能快速升级,赶紧来编辑吧!
strstr是C语言中的函数,作用是返回字符串中首次出现子串的地址。
外文名
strstr
分 类
C语言函数作 用
返回字符串中首次出现子串的地址
包含文件
string.h
函数原型: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 <
显示的是: 34xyz
strstr函数实现
编辑
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 reservedchar *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.0char *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);
}
strstr应用举例
编辑
// strstr.c#include
#include
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”),找到的是onexxxstring2oneyyychar *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;
}