此题 于 2014-11-02 更新。
strStr() 函数实现的功能为,搜索一个字符串在另一个字符串中的第一次出现。若找到所搜索的字符串,则该函数返回第一次匹配的字符串的地址;如果未找到所搜索的字符串,则返回NULL。
代码
class Solution
{
public:
char *strStr(char *haystack, char * needle)
{
int len = strlen(needle);
if(len==0)
return haystack;
for(; *haystack; ++haystack)
{
if(*haystack==*needle && strncmp(haystack, needle, len)==0)
return haystack;
}
return NULL;
}
};
题目更新后的要求是输出出现第一个相同字符串的index
代码
class Solution {
public:
int strStr(char *haystack, char *needle) {
int len = strlen(needle);
if(len==0)
return 0;
int indexOfHay = 0;
while(haystack[indexOfHay]!='\0')
{
if(strncmp(haystack+indexOfHay, needle, len) == 0)
return indexOfHay;
indexOfHay++;
}
return -1;
}
};