使用unordered_map统计单词频率,先分词并清洗标点、转小写,再计数输出。示例用istringstream分割字符串,cleanWord去除非字母数字,toLower统一大小写,最终遍历map打印词频。

在C++中统计单词出现次数,常用的方法是结合标准库中的 std::map 或 std::unordered_map 来记录每个单词的频率。下面是一个简单、实用的实现方式。
从输入流(如字符串或文件)中读取内容,并按空格、换行等分隔符拆分出单词。可以使用 std::istringstream 配合循环自动分割。
示例代码:
#include <iostream>
#include <string>
#include <sstream>
#include <map>
#include <unordered_map>
#include <cctype>
// 将单词转为小写,避免大小写敏感
std::string toLower(const std::string& word) {
std::string lower;
for (char c : word) {
lower += std::tolower(c);
}
return lower;
}
// 移除标点符号
std::string cleanWord(const std::string& word) {
std::string cleaned;
for (char c : word) {
if (std::isalnum(c)) {
cleaned += c;
}
}
return cleaned;
}
将处理后的单词作为键,出现次数作为值存入 std::map 或 std::unordered_map。后者查找更快,适合大数据量。
int main() {
std::string input = "Hello, world! Hello C++ programming. Programming is fun.";
std::istringstream iss(input);
std::string word;
std::unordered_map<std::string, int> freq;
while (iss >> word) {
word = cleanWord(word);
if (!word.empty()) {
freq[toLower(word)]++;
}
}
// 输出结果
for (const auto& pair : freq) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
实际应用中需注意以下几点:
立即学习“C++免费学习笔记(深入)”;
基本上就这些。核心思路是:分词 → 清洗 → 计数 → 输出。C++标准库提供了足够工具,无需手动实现复杂结构。
以上就是c++++中如何统计单词出现次数_c++单词频率统计方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号