这个题目很有意思,先列出笔者的测试案例,这个测试案例在一行前和一行尾都有空格,特别是行尾的空格,如 holly shit 不要输出为3个单词,笔者因此WA好几次
yo u are my friend
fri end you are my friend
you are my friend
holly shit
#
代码:
用了C++ STL中的Set,算是杀鸡用牛刀了。
#include<iostream>
#include<string>
#include<set>
using namespace std;
int main()
{
int pos1, pos2;
set<string> strS;
string lineStr, str;
while(getline(cin, lineStr))
{
if(!strS.empty())
{
strS.clear();
}
for(pos2 = pos1 = 0; pos2 < lineStr.length(); ++pos2)
{
if(lineStr.at(pos2) == '#')
{
return 0;
}
else if(lineStr.at(pos2) == ' ')
{
str = lineStr.substr(pos1, pos2-pos1);
pos1 = pos2+1;
if(!str.empty())
{
strS.insert(str);
}
}
}
str = lineStr.substr(pos1);
if(!str.empty())
{
strS.insert(str);
}
printf("%d\n", strS.size());
}
return 0;
}