2017-08-02 56 views
0

我需要检查给定字符串数组中的元音总数,但我无法弄清楚如何遍历数组中的每个元素......我知道如何遍历字符串数组本身:C++如何循环数组中的字符串?

int countAllVowels(const string array[], int n) 
{ 
    for (int i = 0; i < n; i++) 
    { 
     cout << array[i] << endl; 
    } 
return(vowels); 
} 

但是,我该如何调查数组的每个元素?

+0

std :: string has operator []并知道它的大小。 – 2017-08-02 21:37:03

+0

分解问题:编写一个函数来首先计算单个字符串中的元音。 – hyde

回答

3

可以遍历的std::string

int countAllVowels(const string array[], int n) 
{ 
    static const std::string all_vowels = "aeiou"; 
    int vowels = 0; 
    for (int i = 0; i < n; i++) 
    { 
     for (char c : array[i]) 
     { 
      if (all_vowels.find(c) != std::string::npos) 
       vowels += 1; 
     } 
    } 
    return(vowels); 
} 

每个char或者这可以用几个功能从<algorithm>

std::size_t countAllVowels(std::vector<std::string> const& words) 
{ 
    return std::accumulate(words.begin(), words.end(), 0, [](std::size_t total, std::string const& word) 
      { 
       return total + std::count_if(word.begin(), word.end(), [](char c) 
           { 
            static const std::string all_vowels = "aeiou"; 
            return all_vowels.find(c) != std::string::npos; 
           }); 
      }); 
} 
0

使用两个循环完成,外一个字符串数组,数组中一个特定字符串的内部字符。完整的例子:

#include <iostream> 
#include <vector> 
#include <algorithm> 
#include <string> 
int countAllVowels(std::string array[], int n){ 
    std::vector<char> vowels = { 'a', 'e', 'i', 'o', 'u' }; 
    int countvowels = 0; 
    for (int i = 0; i < n; i++){ 
     for (auto ch : array[i]){ 
      if (std::find(vowels.begin(), vowels.end(), ch) != vowels.end()){ 
       countvowels++; 
      } 
     } 
    } 
    return countvowels; 
} 
int main(){ 
    std::string arr[] = { "hello", "world", "the quick", "brown fox" }; 
    std::cout << "The number of vowels is: " << countAllVowels(arr, 4); 
}