28. Implement strStr()
Difficulty: Easy
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
实现strstr()。返回字符串needle在字符串haystack中第一次出现的位置。如果needle不在haystack中,则返回-1。
注意:
1.C++中的函数strStr(str1,str2):判断字符串str2是否是str1的子串,如果是,返回str2在str1中首次出现的地址;如果不是,返回NULL。
2.strcmp(str1,str2)
str1=str2时,返回0
str1>str2时,返回正数
str1
int strStr(char* haystack, char* needle) {
int i,j,k;
int len1,len2;
len1=strlen(haystack);
len2=strlen(needle);
if(len1<len2)
return -1;
if(len2==0)
return 0;
for(i=0;i<=len1-len2;i++) //
{ //
k=i; //
for(j=0;j<len2;j++) //
{ //
if(haystack[k]!=needle[j])//
break; //
k++; //
} //
if(j==len2) //
return i; //
} //
return -1;
}
中间部分也可以用strncmp()函数替代,如下。
int strStr(char* haystack, char* needle) {
int i,j,k;
int len1,len2;
len1=strlen(haystack);
len2=strlen(needle);
if(len1<len2)
return -1;
if(len2==0)
return 0;
for(i=0;i<=len1-len2;i++) //
{ //
if(strncmp(haystack+i,needle,len2)==0)//
return i; //
} //
return -1;
}