要编写一个单词统计程序,核心步骤包括:1.使用std::istringstream和std::isalpha分割并清洗字符串中的单词;2.通过std::map统计词频;3.遍历map输出结果或按频率排序。具体实现中,先定义cleanword函数过滤非字母字符并统一转小写,再利用map存储单词及出现次数,最后可选择直接输出或复制到vector后排序处理。整个过程需注意分隔符处理、大小写统一及map操作方式。
写一个单词统计程序,核心在于字符串处理和用 map 统计词频。C++ 提供了丰富的字符串操作函数和标准容器,只要合理使用就能实现这个功能。
要统计单词数量,第一步是把输入的字符串按空格、标点等分隔符拆分成一个个单词。常用的函数是 std::istringstream 和 std::isalpha 配合处理。
#include <sstream> #include <cctype> std::string cleanWord(const std::string& word) { std::string cleaned; for (char c : word) { if (std::isalpha(c)) { cleaned += std::tolower(c); // 统一转小写 } } return cleaned; }
这段代码会过滤掉非字母字符,并将所有字母统一为小写,避免 "Hello" 和 "hello" 被当作不同单词。
立即学习“C++免费学习笔记(深入)”;
C++ 中的 std::map 是一种键值对结构,非常适合用来统计每个单词出现的次数。
主流程大概是这样的:
示例代码片段如下:
#include <map> #include <string> std::map<std::string, int> wordCount; std::string word; while (iss >> word) { std::string cleaned = cleanWord(word); if (!cleaned.empty()) { wordCount[cleaned]++; } }
这里用 std::istringstream 来逐个读取单词,再通过前面定义的 cleanWord 做预处理。
遍历 map 的内容很简单,直接用一个循环就可以打印出所有单词及其出现次数:
for (const auto& pair : wordCount) { std::cout << pair.first << ": " << pair.second << std::endl; }
如果想按频率排序,可以先把 map 的内容复制到 vector,然后自定义排序规则:
#include <vector> #include <algorithm> std::vector<std::pair<std::string, int>> items(wordCount.begin(), wordCount.end()); std::sort(items.begin(), items.end(), [](const std::pair<std::string, int>& a, const std::pair<std::string, int>& b) { return b.second < a.second; // 降序排列 }); for (const auto& item : items) { std::cout << item.first << ": " << item.second << std::endl; }
这样就能输出按频率从高到低排好序的结果了。
基本上就这些。整个过程不算复杂,但有几个细节容易忽略,比如标点处理、大小写统一、以及 map 插入方式。把这些地方注意好,程序就能稳定运行了。
以上就是如何用C++编写单词统计程序 字符串处理和map容器使用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号