输入两个字符串,验证其中一个串是否为另一个串的子串。

本文介绍了三种不同的C/C++实现方法,包括使用标准库函数`find`、`strstr`和自定义循环查找,来检查一个字符串是否是另一个字符串的子串。通过实例展示了如何在不同情况下判断子串关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一

#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; 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值