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