题目
思路
首先可以进行长度判断,长度都不一样就不用谈是同一个单词了
然后长度相同就逐个比较即可,需要注意开头和结尾的特殊判断
代码
#include<iostream>
#include<string>
using namespace std;
long long cnt(string & all, string & word)
{
if(word.length() > all.length())
{return 0;}
long long count = 0;
string one = all.substr(0,word.length());
int position_2 = all.find(" ");
if(one == word && (position_2 == word.length() || word.length() == all.length() ))
{count++;}
int position_1 = position_2;
while((position_2) != all.npos)
{
position_2 = all.find(" ",position_1 + 1);
int each_len;
if(position_2 != all.npos)
{
each_len = position_2 - position_1 - 1;
}
else
{
each_len = all.length() - position_1 - 1;
}
string temp = all.substr(position_1 + 1, word.length());
position_1 = position_2;
if(temp == word && each_len == word.length())
{count ++;}
//cout << count << "??? "<< endl;
}
return count;
}
int main()
{
int total;
cin >> total;
getchar();
for(int i = 0; i < total; i++)
{
string all;
getline(cin, all);
//cout << all << endl;
string word;
cin >> word;
getchar();//
//cout << word<<endl;
cout << "case #" << i << ":"<<endl;
cout << cnt (all, word) << endl;
}
return 0;
}