2015-10-07 40 views
0

這是我家的工作,我們的教授希望我們將CIN先得到一個字符串,並輸出在字符串「a」和「c」的數量。例如,如果你有一個sting str =「apple」,並且你想要「p」,你刪除了其他的字母,並且得到一個新的sting,這個str1 = str1 = 「pp」,比使用str.size(),以獲得多少「p」。在C++中如何獲得一個字母組成的字符串

我的問題是我怎麼能刪除其他字母。

+1

這裏是您可以操作的列表在一個'std :: string'上執行:http://www.cplusplus.com/reference/string/string/這應該有助於你的任務。請注意,該列表還強調了您可以替代的其他功能 – Tas

+0

不刪除其他字符會更快。創建一個計數器變量,將其初始化爲'0',然後遍歷字符串並在每次當前字符爲'a'或'c'時添加到計數器變量中 – asimes

回答

1

爲什麼甚至刪除人物?你可以實現你的目標是這樣的:

std::string str; 
std::cin >> str; 
int a_counter = 0; 
for(char& c : str) 
{ 
    if (c == 'a') 
    a_counter++; 
} 

std:: cout << a_counter; 
2

如果你被允許使用std::map,你可以使用:

std:map<char, int> charCount; 
for (auto c : str) 
{ 
    charCount[c]++; 
} 

// Number of times 'a' is found: 
int aCount = charCount['a']; 

// Number of times 'c' is found: 
int cCount = charCount['c']; 
+0

我不認爲我們能夠使用std :: map –

4

如果你只計算一個特定的字母有一個標準庫算法。

int p_count = std::count(str.begin(), str.end(), 'p'); 

有一個相關的算法,接受用於更復雜的用途謂詞:

int ac_count = std::count_if(str.begin(), str.end(), [](char ch){ return ch == 'a' || ch == 'c'; }); 

而對於另一種解決方案中,簡單的數組。這是很快的,並且一次性讀取全部個字母。

int counts[256] = {}; 
for (unsigned char ch : str) { 
    ++counts[ch]; 
} 
cout << "a count is " << counts['a'] << '\n'; 
cout << "c count is " << counts['c'] << '\n'; 
+0

「使用cin首先獲取字符串,並輸出該字符串中的多少」a「和」c「...」 – juanchopanza

+0

@juanchopanza:添加了'std :: count_if'示例。說實話,對於這個作業,我可能會創建'int counts [256];'並遍歷字符串,一次更新計數。 – Blastfurnace

+0

同意。陣列可能是最好的解決方案。 – juanchopanza

1

C++標準庫中有這樣的功能:count

int a_count = std::count(str.begin(), str.end(), 'a'); 
0

其他大部分答案都是偉大的,我強烈建議您使用Blastfurnace's solution;但是,如果你真的想擦除從std::string的chracters除了一組特定的字符(比如「a」和「C」),你可以使用erase-remove idiom

std::string s; 
std::cin >> s; 
s.erase(std::remove_if(s.begin(), s.end(), [](char c){ return c != 'a' || c != 'c'; }), s.end()); 
cout << s.size() << endl; 

有一個answer here進一步解釋(免責聲明:這是我的回答)

+0

非常感謝你! –

0

您可以在將來解決類似問題時使用以下思維過程。

編程可以簡化爲執行3個步驟:

1)輸入數據 2)的過程數據 3)的輸出數據

步驟:

1)瞭解你正在試圖解決什麼在你的意見。

您知道您必須使用「cin」讀取輸入並使用字符串變量進行存儲,然後計算該字符串中字符出現的次數。

2)詳細瞭解用於存儲輸入的變量類型/類。

在您的情況下,您將輸入存儲在字符串類/類型的「字符串」中。轉到C++參考網站,閱讀有關字符串類的知識,並熟悉字符串類提供的所有功能和屬性。請參閱以下link:在那裏您會看到,該字符串類具有返回字符的「[]」運算符。您可以點擊該鏈接並查看如何使用它的示例。

接下來,使用您剛剛獲得的信息處理您的數據。

3)現在執行你的邏輯來處理數據。

在你的情況,你可以循環運行:

std::string str; 

std::cin << std::str; 

int counter = 0; 

for(int i=0; i< str.size();i++) 

{ 

     if(str[i] == 'p') counter++; 

} 

IF塊檢查字符串中的每個字符,並用「P」字符匹配它。如果匹配,則計數器變量加1。最後,「計數器」的值是字符串「str」中出現「p」的次數

0
for(int i=0;i<str.size();i++) 
{ 
    if(str[i]=='a') 
     countOfa++; 
    else if(str[i]=='c') 
     countOfc++; 
} 
cout<<"coun of A is :"<<countOfa<<endl; 
cout<<"coun of C is :"<<countOfc<<endl; 


return 0; 
} 
+0

很好很清楚,謝謝你! –

+0

歡迎您也初始化countOfa和countOfc爲0 – Danika

相關問題