我有一个字符串 vector
例子:
防卫队
edf
联邦 express
防卫队

我想通过列表并计算每个字母出现的次数

所以例如这封信
d 出现 5 次
e 出现 5 次
f 出现 5 次
h出现1次

到目前为止,我还没有任何代码,但我想先看看如何用逻辑来做到这一点。

我正在尝试编码,但不知道从哪里开始。

我在想我可以将每个字母存储到一个字符串中。
字符串将是 {dedfeedffedfhedf}

然后取字符串并计算每个字母在该字符串中的次数
但这是我遇到问题的地方。有什么想法吗?

任何建议也将不胜感激。

谢谢你

最佳答案

您可以使用一个数组来保存每个字母的计数。如果我们只假设字母表,您将有一个包含 26 个元素(可能是整数)的数组,所有元素都初始化为 0。然后您可以遍历每个字符串,每次遇到一个字符时,都会增加该计数。

//let's call your vector of strings stringvec
int counts[26];

//initialize counts to 0

//go through each string in the vector
for (int i = 0; i < stringvec.size(); i++) {
    //get current string
    string curstr = stringvec[i];

    //for each letter in the string
    for (int j = 0; j < curstr.size(); j++) {
        //curstr[j] is a character at position j in the string
        //subtracting 'a' from it will give you the position in relation to 'a' in ASCII, so a character 'a' = 0, 'b' = 1, 'c' = 2, and so on...
        counts[curstr[j] - 'a']++;
    }
}

然后你可以对计数做任何你想做的事情。

关于c++ - 查找字符串 vector 中的字母数 c++,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9088033/

10-15 00:05
查看更多