【C++】STL string类例题新思路记录(编写一个程序,告诉用户输入的句子包含多少个元音字母)

vangoghpeng / 2024-02-10 / 原文

题干:编写一个程序,告诉用户输入的句子包含多少个元音字母。

 方案一:

1、创建一个普通函数,依次传入5个元音字母对查找字符串进行检测。

2、函数通过依次传入的单个元音字母,循环查找整个字符串最后返回统计值。

 1 #include <string> 
 2 #include <iostream> 
 3 using namespace std;
 4 int GetNumCharacters(string& strInput, char chToFind)
 5 {
 6     int nNumCharactersFound = 0;
 7     size_t nCharOffset = strInput.find(chToFind);
 8     while (nCharOffset != string::npos)
 9     {
10         ++nNumCharactersFound;
11         nCharOffset = strInput.find(chToFind, nCharOffset + 1);
12     }
13     return nNumCharactersFound;
14 }
15 int main()
16 {
17     string strInput("atooota");
18     int nNumVowels = GetNumCharacters(strInput, 'a');
19     nNumVowels += GetNumCharacters(strInput, 'e');
20     nNumVowels += GetNumCharacters(strInput, 'i');
21     nNumVowels += GetNumCharacters(strInput, 'o');
22     nNumVowels += GetNumCharacters(strInput, 'u');
23     cout << "The number of vowels in that sentence is:" << nNumVowels;
24     return 0;
25 }

上述方案有些缺陷:

1、mian作用域中的代码有些臃肿并且重复性很高,让人看着很不舒服。

 

改进思路:

1、避免重复性代码,即避免对函数的多次调用,且一次性将元音字母全部传入后继续计数。

 1 #include <iostream>
 2 #include <string>
 3 #include <algorithm>
 4 
 5 int CountVowels(const std::string& str, std::string& num) {
 6     int count = 0;
 7     for (char c : str)
 8         if (std::find(std::begin(num), std::end(num), c) != std::end(num))
 9             count++;
10     return count;
11 }
12 
13 int main() {
14     using namespace std;
15 
16     string sentence("ATOTOTA");
17     string vowels = "aeiouAEIOU";
18     int numVowels = CountVowels(sentence, vowels);
19 
20     cout << "句子中包含 " << numVowels << " 个元音字母。" << endl;
21 
22     return 0;
23 }

上述代码对比之下就简洁了许多,改进点包括:

1、将大小写元音字母一次性传入。

2、将用单个元音查找str修改为,str依次去和元音字符串进行find