问题链接:HDU2072 单词数。
问题简述:参见上述链接。
问题分析:
这是一个比较简单的问题,一行一行读入字符串,统计该行有几个单词。单词之间只有空格分割。
程序说明:
解法一:
程序中,使用C语言的库函数strtok来切割字符串。另外统计字符串时,需要过滤相同的单词,所有用C++的字符串集合(set
这个程序既使用C语言的库函数,也使用C++容器中的集合set。但是,这种做法只能说是做了一个基础练习,未必是最佳方案。还有一种做法是纯粹的C++编程。
使用C语言的库函数strtok来切割字符串的好处在于,可以指定任意字符作为分隔符来切割单词。
解法二:
程序中使用set、
AC的C++语言程序如下(解法二):
/* HDU2072 单词数 */
#include
#include
#include
#include
using namespace std;
int main()
{
string s;
while(getline(cin, s) && s != "#") {
istringstream sin(s);
set words;
string w;
while(sin >> w)
words.insert(w);
cout << words.size() << endl;
}
return 0;
}
AC的C++语言程序如下(解法一):
/* HDU2072 单词数 */
#include
#include
#include
#include
#include
using namespace std;
int main(void)
{
char buf[1024];
char pound[] = "#";
char delim[] = " ";
char *p;
set words;
while(gets(buf) != NULL) {
if(strcmp(buf, pound) == 0)
break;
words.clear();
p = strtok(buf, delim);
while(p) {
words.insert(p);
p = strtok(NULL, delim);
}
cout << words.size() << endl;
}
return 0;
}