单词识别:map 统计文中出现单词个数

本文介绍了一种统计英文句子中单词出现频率的方法,通过两个不同的代码示例展示了如何使用C++实现单词计数,并按字典序输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

输入一个英文句子,把句子中的单词(不区分大小写)按出现次数按从多到少把单词和次数在屏幕上输出来,要求能识别英文句号和逗号,即是说单词由空格、句号和逗号隔开。
输入描述:
输入有若干行,总计不超过1000个字符。

输出描述:

输出格式参见样例。

输入

A blockhouse is a small castle that has four openings through which to shoot.

输出

a:2
blockhouse:1
castle:1
four:1
has:1
is:1
openings:1
shoot:1
small:1
that:1
through:1
to:1
which:1

题目详情:

https://www.nowcoder.com/practice/16f59b169d904f8898d70d81d4a140a0?tpId=94&tqId=31064&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fbit-kaoyan%2Fquestion-ranking&tPage=2

心得体会:
  1. 代码一的设计思想是源自刘汝佳的算法书。要熟练利用 stringstream
  2. 注意 tolower 和 toupper 并不是要求参数必须是字母,非字母的字符也可以,只是这时会原样输出。比如 toupper 该函数等效返回大写字母,如果存在这样的值。否则保持不变
  3. map默认对键进行了排序,所以不需要调用sort。除非改变排序方式或者对值进行排序
代码一:
#include<iostream>
#include<algorithm>
#include<string>
#include<sstream>
#include<map>

using namespace std;
int main()
{
	string s,sum;
	map<string, int>n;
	while (cin >> s)
	{
		for (int i = 0; i < s.length(); i++)
		{
			if (isalpha(s[i]))
				s[i] = tolower(s[i]);
			else if (s[i] == ',' || s[i] == '.')
				s[i] = ' ';
		}
		stringstream ss(s);
		while (ss >> sum)
		{
			if (!n.count(sum))
				n[sum] = 0;
			n[sum]++;
		}
	}
	for (map<string, int>::iterator it = n.begin(); it != n.end(); it++)
		cout << (*it).first << ":" << (*it).second << endl;
	return 0;
}
心得体会:
  1. 代码二是牛客网一个大佬写的。比我的要简洁的多
  2. #include <bits/stdc++.h> 是一个万能的头文件。大部分编译器和OJ都支持。POJ 不支持,HDU 只有G++支持。其他基本都支持
  3. 单词统计的话以后都可以用代码二实现,很方便
代码二:
//这道题的答案是按照字典序排列的,只要将map中的元素顺序输出即可。
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    string s;
    while(getline(cin, s))
    {
        map<string, int> mp;
        string temp;
        for(int i = 0; i < s.size(); i++)
        {
            if(s[i] == ' ' || s[i] == ',' || s[i] == '.')   // 核心 
            {									// 遇到分隔符的话把一个单词赋值到map
                if(temp != "")    
                    mp[temp]++;
                temp = "";
            }
            else                               //非分隔符的话把字符合成一个单词(字符串)
            {
                temp += tolower(s[i]);        // 非字母字符的话不变直接赋值
            }
        }
        for(auto it = mp.begin(); it != mp.end(); it++)
        {
            cout << it->first << ":" << it->second << endl;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值