包含文件:
string.h
函数名: strstr
函数原型:
1
|
extern
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的第一次出现的位置,并返回此str1在str2首位置的地址。;如果str2不是str1的子串,则返回NULL。
例子:
1
2
3
|
char
str[]=
"1234xyz"
;
char
*str1=
strstr
(str,
"34"
);
cout << str1 << endl;
|
显示的是一串地址:-1076038504(每次不一定一样)
函数实现
1.Copyright 1990 Software Development Systems, Inc.
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;
}
|
2.Copyright 1986 - 1999 IAR Systems. All rights reserved
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;
}
|
3. GCC-4.8.0
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_t len=
strlen
(s2);
for
(;(p=
strchr
(p,*s2))!=0;p++)
{
if
(
strncmp
(p,s2,len)==0)
return
(
char
*)p;
}
return
(0);
}
public int strStr(String hayStack, String needle) {
for ( int i = 0; ; i++) {
for (int j = 0; ; j < needle.length()) {
if (j == needle.length()) {
return i;
} else if (i + j == hayStack.length()) {
return -1;
}
if (hayStack.charAt(i) != needle.charAt(i + j)) {
break;
}
}
}
return i;
}
|