1140:验证子串

方法一:自己写

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

       }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值