21xrx.com
2025-06-30 15:09:11 Monday
文章检索 我的文章 写文章
C++实现字符串中每个字符出现次数统计
2023-07-10 18:11:34 深夜i     46     0
C++ 字符串 字符 出现次数统计

在C++编程中,对字符串中每个字符出现次数进行统计是一个常见的需求,本文将介绍如何使用C++语言实现此功能。

首先,我们需要定义一个函数来实现字符串中每个字符出现次数的统计。该函数的参数为一个字符串,返回值为一个集合,集合中包含每个字符和该字符在字符串中出现的次数。

代码如下:

#include <iostream>
#include <unordered_map>
using namespace std;
unordered_map<char, int> countChars(string str) {
  unordered_map<char, int> charCount;
  for (char c : str) {
    charCount[c]++;
  }
  return charCount;
}
int main() {
  string s = "hello world";
  auto counts = countChars(s);
  for (auto& p : counts)
    cout << p.first << " occurs " << p.second << " times" << endl;
  
  return 0;
}

在上述代码中,我们定义了一个 `countChars` 函数,该函数使用一个哈希表来存储每个字符和它在字符串中出现的次数。接着,我们可以在 `main` 函数中调用 `countChars` 函数,并对返回的哈希表进行遍历打印输出。

运行该程序,输出结果如下:

occurs 1 times
d occurs 1 times
e occurs 1 times
h occurs 1 times
l occurs 3 times
o occurs 2 times
r occurs 1 times
w occurs 1 times

可以看到,这段程序成功统计出了字符串中每个字符出现的次数。

以上就是C++实现字符串中每个字符出现次数统计的方法,使用哈希表是其中的关键点。在实际应用中,我们可以根据实际需要对该算法进行优化和改进。

  
  

评论区