strStr 我压根就不知道有这么个奇葩函数,好像是找子串位置,但不是有find么= =
结果我就想用find去实现,对于需求还是有点费解,"a" "" 居然是返回”a“ 按道理就是找不到啊。后来想想,可能是因为空串,然后空串是任何字符串的子串(不包含NULL,因为NULL本身就是没有内容的,空串是有一个结束符,长度为0) 有点玩数学定义游戏的味道= =
然后看说明返回,结果我还把后面的字符串截断了,后来再仔细看看定义,发现不是的,只是返回从pos开始的字符串位置,也即指针,后面不管。
另外这里还学到了string::npos 是内置表示 no pos的一个static int,cplusplus里 说是-1 但实际debug 好像是int 上界附近的数
char *strStr(char *haystack, char *needle) {
if(strlen(needle)==0)return haystack;
string haystack_str=haystack,needle_str=needle;
int index=haystack_str.find(needle_str);
//cout<<"index: "<<index<<" npos: "<<string::npos<<endl;
if(index==string::npos)return NULL;
//haystack[index+needle_str.length()]='\0';
return haystack+index;
}
今天再次看到July大大的帖子涉及到各种C字符串库函数实现
http://blog.csdn.net/v_july_v/article/details/6417600
后来发现当时自己直接调用string的find函数,其实不是个人实现,严格来说不能调用库函数的。对于这篇博客读者反馈@xiaohui5319 非常赞同,
July大神可能确实日理万机,某些细节地方也没有那么多都去管。首先库函数确实是饭后char*, strlen的问题确实有,第一可能当时还没设计出来,第二效率太低了,然后strlen返回确实是size_t, 这个是unsingned int 的同义词,好像多数情况是C++的unsigned int类型,比int整数差不多多一倍的范围,赋值可能溢出,下面是我重新写的代码,虽然由于效率低,没有用KMP而TLE了= = 先暂时满足面试官考察的部分要求再说,上面肯定是不合格的
char * STRSTR (const char *haystack_start, const char *needle_start)
{
if(haystack_start[0]=='\0'||needle_start[0]=='\0') return NULL;
int j;
for(int i=0;haystack_start[i]!='\0';i++)
{
int haystack_starti=i;
for(j=0;needle_start[j]!='\0';j++)
{
if(haystack_start[haystack_starti]!=needle_start[j])
break;
else
haystack_starti++;
}
if(needle_start[j]=='\0')//matched
{
char *haystack_startcp=(char*)haystack_start;
return haystack_startcp+haystack_starti;
}
}
return NULL;
}