寻找子串位置

1204 寻找子串位置

题目描述 Description

给出字符串a和字符串b,保证b是a的一个子串,请你输出b在a中第一次出现的位置。

输入描述 Input Description

仅一行包含两个字符串a和b

输出描述 Output Description

仅一行一个整数

样例输入 Sample Input

abcd bc

样例输出 Sample Output

2

数据范围及提示 Data Size & Hint

字符串的长度均不超过100



AC代码:


#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int main()
{
	char str[110],st[110];
	int i,t,j,len,cnt;
	scanf("%s%s",&str,&st);
	len=strlen(str);
	j=strlen(st);
	for(i=0,t=0;i<len;++i)
	{
		if(str[i]==st[t])
		{
			if(!t)cnt=i+1;
			t++;
			if(t==j-1)
			{
				printf("%d\n",cnt);
				break;
			}
		}
		else if(t)//这个一开始没想到,当t不为0时i必须要退一位
		{
			i--;
			t=0;
		}
		else
		{
			t=0;
		}
	}
  return 0;
}

简单代码:

#include<iostream>
#include<string>
using namespace std;

int main()
{
    string a,b;
    cin >> a >> b;
    int n = a.find(b);
    cout << n+1 << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值