c++||实现一个函数,能统计一段文字中,某个单词的出现次数。记录各单词出现频率新手初级

1.所需的知识:

unordered容器的基本认识和初步使用

stringstream的相关知识

2.代码实现

#include<iostream>
#include<sstream>
#include<fstream>
#include<string>
#include<iterator>
#include<unordered_map>
#include <stdio.h>
using namespace std;


//介绍unordered容器:键值和数据,可通过键值来直接找到数据
//unordered_map<string, int>  



unordered_map<string, int> strMap;     //用于保存结果

void countword(stringstream& ss)
{
    string tmp;
    while (ss >> tmp)   //将stringstream ss的字符串以空格为间隔的单词放入tmp中
    {
        unordered_map<string, int>::iterator it = strMap.find(tmp);
        if (it == strMap.end())
        {
            strMap.insert(unordered_map<string, int>::value_type(tmp, 1));   //通过迭代器将新的键值tmp和数据1放入容器
        }
        else
        {
            strMap[tmp]++;
        }
    }
}

int main()
{
    //读入字符串
    string str1;
    cout << "enter a string :";
    getline(cin,str1);                               //要用getline()函数输入带空格的字符串,cin无法输入带空格的字符串

    //去除符号
    for (int i = 0; i < str1.length(); i++)     //字符串的长度str1.legnth()
    {
        if (int(str1[i]) < 64 && int(str1[i]) > 91 || int(str1[i]) < 96 && int(str1[i]) > 122)
        {
            str1[i] =' ';                        //在c++中单引号表示字符双引号表示字符串
        }
    }

    //进行统计
    stringstream ss(str1);              //stringstream类型的ss获取str1的字符串数据
    countword(ss);
    //打印
    unordered_map<string, int>::iterator it = strMap.begin();
    for (it;it != strMap.end(); it++)
    {
        cout << "单词:" << it->first <<"出现了" << it->second<<"次";
        cout << endl;
    }

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值