首页 > 解决方案 > 是否有一种有效的方法来检查正在使用的字母?

问题描述

假设我有一个 string string str;,其中包含任意数量的字母,我想计算字符串中每个字母的数量。例如,单词"Example"有 2 'e'、 1 'x'、 1 'a'、 1 'm'、 1'p'和 1 'l'。有没有比这更有效的方法来检查每个字母?

for (int i = 0; i < str.length(); i++)
{
    if (str.at(i) == 'a')
    {
        //variable which keeps track of a ++
    }...
    //25 more of that for each other letter
}

感觉必须有一种更有效的方法来做到这一点,但我不知道怎么做。请赐教。

标签: c++stringletter

解决方案


您可以使用std::map例如:

#include <map>

std::map<char, std::size_t> mCount{};
for (auto ch : str)
{
   ++mCount[ch];
}

使用 a std::array(其优点是数据在内存中是连续的,从而提高缓存性能)您可以编写:

#include <array>
#include <limits>

constexpr auto nNumChars = static_cast<std::size_t>(std::numeric_limits<unsigned char>::max()) + 1;
std::array<std::size_t, nNumChars> arCounts{};

for (auto ch : str) {
   ++arCounts[static_cast<unsigned char>(ch)];
}

推荐阅读