为什么改判断条件就对了
查看原帖
为什么改判断条件就对了
527115
Hello_cbn楼主2023/12/15 22:11

本人代码:

#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)就对了?

2023/12/15 22:11
加载中...