Reputation: 1
I'm required to check for the total number of vowels in a given string array but I can't figure out how to loop through each element of the array...I know how to loop through a string array itself:
int countAllVowels(const string array[], int n)
{
for (int i = 0; i < n; i++)
{
cout << array[i] << endl;
}
return(vowels);
}
But how do I actually investigate each element of the array?
Upvotes: 0
Views: 3197
Reputation: 117856
You can loop through each char
of the 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);
}
Alternatively this be done using a couple of functions from <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;
});
});
}
Upvotes: 3
Reputation: 15501
Use two loops, the outer one for the array of strings, the inner one for the characters of a particular string in an array. Complete example:
#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);
}
Upvotes: 1