在字符串中进行子串查找

来源:百度知道 编辑:UC知道 时间:2024/05/30 09:28:20
各位大虾帮忙看一下错在哪里~~~`
#include<iostream>
using namespace std;
char *strstr(char *string,char *substring)
{
while(*string!='\0')
{
while(*substring!='\0')
{
if(*string==*substring)
{
string++;
substring++;
}
else
{
string++;
}
}

if(substring=='\0') return string;
else return NULL;
}
}
void main()
{
char str1[100],str2[100];
char *p;
cout<<"————查找第二个字符串在第一个字符串的位置系统————"<<endl;
cout<<"请输入第一个字符串:"<<endl;
cin>>str1;
cout<<"请输入第二个字符串:"<<endl;
cin>>str2;
p=strstr(str1,str2);
if(p==NULL)
cout<<"第一个字符串中不存在第二个字符串"<<endl;
else
cout<<"第二个字符串在第一个字符串中开始的位置为:"<<*p<<endl;
}
第一个回答改变了我的函

你母串和子串一起往后走是不对的,应该母串一个一个往后走,判断接下来的几个字母是否和子串的相同:
这是我写的版本:

#include<iostream>
using namespace std;
int strstr(char *string,char *substring)
{
int len1=strlen(string);
int len2=strlen(substring);
for (int i=0; i<=len1-len2; i++)
{
for (int j=0; j<len2; j++)
{
if (string[i+j]!=substring[j])
break;
}
if (j==len2)
return i+1;
}
return 0;
}
void main()
{
char str1[100],str2[100];
int place;
cout<<"————查找第二个字符串在第一个字符串的位置系统————"<<endl;
cout<<"请输入第一个字符串:"<<endl;
cin>>str1;
cout<<"请输入第二个字符串:"<<endl;
cin>>str2;
place=strstr(str1,str2);
if(place==0)
cout<<"第一个字符串中不存在第二个字符串"<<endl;
else
cout<<"第二个字符串在第一个字符串中开始的位置为:"<<place<<endl;
}