2012-01-31 73 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