- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ Program to count Vowels in a string using Pointer?
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
#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
Advertisements