
方法一
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
using namespace std;
int main(){
string a,b;
cin>>a>>b;
if(a.find(b)!=-1)
cout<<b<<" is substring of "<<a<<endl;
else if(b.find(a)!=-1)
cout<<a<<" is substring of "<<b<<endl;
else
cout<<"No substring"<<endl;
return 0;
}
方法二
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define max 201
int main() {
char str[max], str1[max];
gets(str);
gets(str1);
int len1 = strlen(str);
int len2 = strlen(str1);
if(len1>=len2)
{
if(strstr(str,str1)!=NULL) //找出str1字符串在str字符串第一次出现的位置,若找不到,返回空指针
printf("%s is substring of %s", str1,str);
else
printf("No substring");
}
else
{
if(strstr(str1,str)!=NULL) //否则(len1<len2)找出str字符串在str1字符串第一次出现的位置,若找不到,返回空指针
printf("%s is substring of %s",str,str1);
else
printf("No substring");
}
return 0;
}
方法三
方法二 (有bug没找出来)
#include<iostream>
#include<stdio.h>
#include<math.h>
#include<string.h>
using namespace std;
int main(){
int i,j;
char a[1100],b[1100];
cin.getline(a,1100);
cin.getline(b,1100);
int l1=strlen(a),l2=strlen(b),flag = 0;
// printf("%d %d\n",l1,l2);
if(l1>l2){ //判断b是不是a的子串
for(i = 0;i<l1;i++){
if(a[i]==b[0]){
int num = i;
for(j=0;j<l2;j++){ //循环l2的长度
if(a[num]==b[j]){
num++;
}
}
if((num-i)==l2){
flag = 1;
break;
}
}
}
if(flag){
printf("%s is substring of %s",b,a);
}else{
printf("No substring");
}
}else if(l1<l2){
for(i = 0;i<l2;i++){
if(b[i]==a[0]){
int num = i;
for(j=0;j<l1;j++){ //循环l1的长度
if(b[num]==a[j]){
num++;
}
}
if((num-i)==l1){
flag = 1;
break;
}
}
}
if(flag){
printf("%s is substring of %s",a,b);
}else{
printf("No substring");
}
}else{
printf("No substring");
}
return 0;
}