Advertisement
janac

Find words starting with a vowel

Nov 4th, 2021 (edited)
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.88 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. using namespace std;
  5.  
  6. // Take a list of words and return a list of words
  7. // that start with a vowel.
  8.  
  9. // This function takes a character and returns
  10. // true if it is a vowel. Otherwise, it returns false.
  11. int is_vowel(char letter)
  12. {
  13.     // The character must be one of these.
  14.     string vowels = "AaEeIiOoUu";
  15.  
  16.     // Go from the beginning to the
  17.     // end of the list of vowels.
  18.     for (size_t i = 0; i < vowels.size(); ++i)
  19.     {
  20.         // If the letter matches that vowel.
  21.         if (letter == vowels[i])
  22.         {
  23.             // The letter is a vowel.
  24.             return true;
  25.         }
  26.     }
  27.  
  28.     // The letter didn't match any vowel.
  29.     return false;
  30. }
  31.  
  32. // This function takes a list of words and returns a
  33. // list of the words that start with a vowel.
  34. vector<string> get_vowel_words(vector<string>& word_list)
  35. {
  36.     // These are the words that start with vowels.
  37.     vector<string> words_starting_with_vowels;
  38.  
  39.     // We are testing this word.
  40.     string current_word;
  41.  
  42.     // This is the first letter of the word.
  43.     char first_letter = ' ';
  44.  
  45.     // Go from the beginning to the end of the word list.
  46.     for (size_t i = 0; i < word_list.size(); ++i)
  47.     {
  48.         // Test the next word.
  49.         current_word = word_list[i];
  50.  
  51.         // Get the first letter of the word.
  52.         first_letter = current_word[0];
  53.  
  54.         // If the first letter is a vowel,
  55.         if (is_vowel(first_letter))
  56.         {
  57.             // Add the word to the new list.
  58.             words_starting_with_vowels.push_back(current_word);
  59.         }
  60.     }
  61.  
  62.     return words_starting_with_vowels;
  63. }
  64.  
  65. int main()
  66. {
  67.     // Create a list of words.
  68.     vector<string> words = { "red", "blue", "orange", "yellow" };
  69.  
  70.     // Get a list of the words that start with a vowel.
  71.     vector<string> vowel_words = get_vowel_words(words);
  72.  
  73.     // Display the words that start with a vowel.
  74.     for (size_t i = 0; i < vowel_words.size(); ++i)
  75.     {
  76.         cout << vowel_words[i] << endl;
  77.     }
  78.  
  79.     return 0;
  80. }
  81.  
  82.  
  83.  
  84.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement