2017-08-02 57 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); 
}