本人代码:
#include<bits/stdc++.h>
using namespace std;
string a,b;
int start = 0,ans = -1,cnt = 0;
int main()
{
getline(cin,a);
getline(cin,b);
transform(a.begin(),a.end(),a.begin(),::tolower);
transform(b.begin(),b.end(),b.begin(),::tolower);
while(start != b.length())
{
start = b.find(a,start);
if(start == 0)
if(b[start + a.length()] == ' ')
{
if(ans == -1)
ans = start;
cnt++;
}
if(start == b.length() - 1)
{
if(b[start - 1] == ' ')
{
if(ans == -1)
ans = start;
cnt++;
}
}
else
{
if((b[start - 1] == ' ') && (b[start + a.length()] == ' '))
{
cnt++;
if(ans == -1)
ans = start;
}
}
if(start == -1) break;
start++;
}
if(ans != -1)
cout<<cnt<<" "<<ans;
else
cout<<ans;
return 0;
}
为什么将36行的else改成if(start != 0 && start != b.length() - 1)就对了?