程序员面试宝典:实现C++中的strstr()函数

//注意:检测函数值返回值是否NULL,当返回值为NULL时不能输出。

#include<iostream>
using namespace std;

char * mystrstr( char * str, char * sub)
{
  for( int i = 0; str[i] != '\0'; ++i )
{
  int j = 0;
  int tmp = i;

if( str[i] == sub[j] )
{

  while( str[i++] == sub[j++] )
  {
    if( sub[j] == '\0' )
  {
return &str[i-j];
}

}

  i = tmp;
}
}

return NULL;
}

int main()
{
char str[] = "123456";
char sub[] = "34";
char * tmp = NULL;

tmp = mystrstr(str,sub);

if( tmp == NULL )
{
cout<<"nothing"<<endl;
}
else
{
cout<<tmp<<endl;
}

system("pause");

return 0;
}

posted @ 2013-04-08 09:44  NinaGood  阅读(315)  评论(0)    收藏  举报