大家好,又见面了,我是你们的朋友全栈君。
strstr(str1,str2) 函数用于判断字符串str2是否是str1的子串。如果是,则该函数返回str2在str1中首次出现的地址;否则,返回NULL。
语法
1 | strstr(string,search) |
|
参数
|
描述
|
|---|---|
|
string
|
必需。规定被搜索的字符串。
|
|
search
|
必需。规定所搜索的字符串。
|
提示
search若是数字,所搜索的将是该数字(作为ASCII码)代表的字符。
实例
|
1
|
<?php echo strstr("Helloworld!","world");?>
|
|
1
|
world!
|
string.h
1 | extern char *strstr(char *str1, const char *str2); |
|
1
|
* strstr(str1,str2)
|
|
1
2
3
|
char str[]="1234xyz";
char *str1=strstr(str,"34");
cout << str1 << endl;
|
函数实现
|
1
2
3
4
5
6
7
8
9
10
11
12
|
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;
}
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
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;
}
|
|
1
2
3
4
5
6
7
8
9
10
11
|
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,len)==0)
return (char*)p;
}
return(0);
}
|
应用举例
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include <syslib.h>
#include <string.h>
main()
{
char *s="GoldenGlobalView";
char *l="lob";
char *p;
clrscr();
p=strstr(s,l);
if(p)
printf("%s",p);
else
printf("NotFound!");
getchar();
return0;
}
|
|
1
2
3
4
5
6
7
|
char *s=”string1onexxxstring2oneyyy”;
char *p;
p=strstr(s,”yyy”);
if(p!=NULL)
printf(“%s”,p);
else
printf("notfound\n");
|
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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;
}
|
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/153021.html原文链接:https://javaforall.net
