方法一:自己写
#include<string.h>
#include<iostream>
using namespace std;
int main()
{
char s1[201];
char s2[201];
cin.getline(s1,201);
cin.getline(s2,201);
int len1=strlen(s1);
int len2=strlen(s2);
int num=1;
if(len1<len2)
{
for(int i=0;i<len2;i++)
{
if(s1[0]==s2[i])//在s2数组中找到s1数组中的第一个字符
{
for(int j=1;j<=len1;j++)
{
if(s1[j]==s2[j+i])//在s1和s2都有一个相同字符后,都同时比较下一个字符是不是相同
{
num++;
}
else
{
break;
}
if(num==len1)
{
cout<<s1<<" is substring of " <<s2;
return 0;
}
}
}
}
}
if(len1>len2)
{
for(int i=0;i<len1;i++)
{
if(s2[0]==s1[i])
{
for(int j=1;j<=len2;j++)
{
if(s2[j]==s1[j+i])
{
num++;
}
else
{
break;
}
if(num==len2)
{
cout<<s2<<" is substring of " <<s1;
return 0;
}
}
}
}
}
if(len1==len2)
{
cout<<s1<<" is substring of " <<s2;
return 0;
}
else
cout<<"No substring";//以上三种情况都不是的时候,输出该选项
return 0;
}
方法二:利用strstr函数 str(str2,str1)--->在str2中查找str1
#include<string.h>
#include<iostream>
using namespace std;
int main()
{
char s1[201];
char s2[201];
cin.getline(s1,201);
cin.getline(s2,201);
int len1=strlen(s1);
int len2=strlen(s2);
if(strstr(s2,s1))
{
cout<<s1<<" is substring of "<<s2<<endl;
return 0;
}
if(strstr(s1,s2))
{
cout<<s2<<" is substring of "<<s1<<endl;
return 0;
}
cout<<"No substring"<<endl;
return 0;
}