我需要检查给定字符串数组中元音的总数,但我无法弄清楚如何循环遍历数组的每个元素...我知道如何遍历字符串数组本身:
int countAllVowels(const string array[], int n)
{
for (int i = 0; i < n; i++)
{
cout << array[i] << endl;
}
return(vowels);
}
但是我如何实际调查数组的每个元素?
答案 0 :(得分:3)
您可以遍历char
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);
}
或者,可以使用<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;
});
});
}
答案 1 :(得分: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);
}