2012-01-31 26 views
3

我有一个字符串矢量 例如: dedf EEDF FEDF hedf查找字符串矢量的字母数C++

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

所以例如字母 d出现5次 e出现在5倍 显示f 5倍 h将出现1次

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

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

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

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

任何建议也将不胜感激。

谢谢

+2

这是一个家庭作业)? – 2012-01-31 22:36:02

+0

它是一个项目的一部分。 – Claud 2012-02-01 00:45:19

回答

2

你可以有一个数组来保存每个字母的计数。如果我们假设只是字母表,你会得到一个由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']++; 
    } 
} 

然后你做任何你想要的计数。

2

你可以这样做的几种方法(伪代码,当然):

for each letter you are interested in: 
    for each character in the string: 
     if letter matches character: 
      increment counter 
    print letter and counter 

declare array of counters, one for each letter 
for each character in the string: 
    if character is a letter: 
     increment that counter in the array 
print counters from array 

sort the characters in the string 
for each character in the sorted string: 
    if character is a letter: 
     count the number of times that letter occurs 
     print letter and count 

每一种方法会有不同的性能特点。一些交易空间(在一个计数器阵列)额外的时间(嵌套循环或排序)。看看你能否确定哪一个对你的情况有最佳表现。

5

一般的算法可能是:

create empty array/map/storage container for counting 
for each string in the vector 
    for each character in the string 
     counter[character] += 1 
0

你需要的数据结构,它允许你映射了一封信给一个计数。遍历矢量,遍历字符串中的每个字符,然后查看地图中的字符,并增加计数。

1

使用数组来存储字母数是很明智的,这样您就可以访问O(1)中随机选择字母的数量。

int letters[26] = {0}; 
... 
char c; 
if (c >= 'a' && c <= 'z') 
    letters[c - 'a']++; 
... 
return 0; 

检查this lecture by Richard Buckland (video) - 15:20开始,这将有助于你的一部分;

1
#include <iostream> 
#include <vector> 
#include <string> 
#include <unordered_map> 

using namespace std; 

typedef vector<string> StrVector; 
typedef unordered_map<char, int> CharIntMap; 

int main() { 
    //the following code will work only with a c++11 compiler 
    StrVector words = {"dedf", "eedf", "fedf", "hedf"}; 
    CharIntMap counts; 
    for (string &word : words) { 
     for (char &letter : word) { 
      counts[letter]++; 
     } 
    } 
    for (auto it : counts) { 
     cout << "Count of letter " << it->first << " = " << it->second << endl; 
    } 
    return 0; 
} 
+0

我认为你的意思是'cout <<“Count of letter”<< it.first <<“=”<< it.second <<“\ n”;'否则+1。 – 2012-02-01 01:42:17