C++ Program to count Vowels in a string using Pointer?

C++Server Side ProgrammingProgramming

To get the vowels from a string, we have to iterate through each character of the string. Here we have to use pointers to move through the string. For this we need C style strings. If the string is pointed by str, then *str will hold the first character at the beginning. Then if str is increased, the *str will point next character and so on. If the character is in [a,e,i,o,u] or [A, E, I, O, U] then it is vowel. So we will increase the count

Algorithm

countVowels(str)

begin
   count := 0
   for each character ch in str, do
      if ch is in [a,e,i,o,u] or [A, E, I, O, U], then
         count := count + 1
      end if
   done
   return count
end

Example

 Live Demo

#include<iostream>
using namespace std;
int countVowels(const char *myStr){
   int count = 0;
   while((*myStr) != '\0'){
      if(*myStr == 'a' || *myStr == 'e' || *myStr == 'i' || *myStr == 'o' || *myStr == 'u' || *myStr == 'A' || *myStr == 'E' || *myStr == 'I' || *myStr == 'O' || *myStr == 'U') {
         count++;
      }
      myStr++;
   }
   return count;
}
main() {
   string myStr;
   cout << "Enter String: ";
   cin >> myStr;
   cout << "Number of Vowels: " << countVowels(myStr.c_str());
}

Output

Enter String: EDucation
Number of Vowels: 5
raja
Published on 25-Jul-2019 09:58:39
Advertisements