#2072 单词数(字符串流使用)

单词数

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)

Total Submission(s): 35848    Accepted Submission(s): 8656


Problem Description
lily的好朋友xiaoou333最近很空,他想了一件没有什么意义的事情,就是统计一篇文章里不同单词的总数。下面你的任务是帮助xiaoou333解决这个问题。
 


Input
有多组数据,每组一行,每组就是一篇小文章。每篇小文章都是由小写字母和空格组成,没有标点符号,遇到#时表示输入结束。
 


Output
每组只输出一个整数,其单独成行,该整数代表一篇文章里不同单词的总数。
 


Sample Input
you are my friend
#
 


Sample Ouput
4
 

解法一:STL中的set容器配合sstream字符串流

#include<iostream>
#include<string>
#include<sstream>
#include<set>
using namespace std;
int main() {
    string s,w;
    while (getline(cin ,s) && s != "#") {
        //getchar();
        istringstream sin(s);
        set<string>words;
        while (sin >> w)//我们使用字符串流应该是sin
            words.insert(w);
        cout << words.size() << endl;
    }

    return 0;
}

解法二:C语言函数strtok切割字符串:优点在于指定任意字符为分割点

#include <cstdio>
#include <cstring>
#include <iostream>
#include <set>
#include <string>

using namespace std;

int main(void)
{
    char buf[1024];
    char pound[] = "#";
    char delim[] = " ";
    char *p;

    set<string> 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;
}

//此代码来源网络
posted @   RioTian  阅读(73)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· Obsidian + DeepSeek:免费 AI 助力你的知识管理,让你的笔记飞起来!
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 全程不用写代码,我用AI程序员写了一个飞机大战
点击右上角即可分享
微信分享提示