Remove the vowels from a string in C++
Understanding Vowel Removal
Vowel removal involves deleting all vowels (a, e, i, o, u) from a given string.
We will explore three different methods to remove vowels from a string using C++.
Method 1: Using a Loop
This method iterates through the string and constructs a new string without vowels.
#include <iostream> #include <string> using namespace std; void removeVowels(string str) { string result = ""; for (char c : str) { if (string("aeiouAEIOU").find(c) == string::npos) { result += c; } } cout << "String without vowels: " << result << endl; } int main() { string str; cout << "Enter a string: "; getline(cin, str); removeVowels(str); return 0; }
Output: String without vowels: Hll Wrld
Method 2: Using Recursion
This method removes vowels recursively.
#include <iostream> #include <string> using namespace std; void removeVowelsRecursive(string &str, int index) { if (index >= str.length()) return; if (string("aeiouAEIOU").find(str[index]) != string::npos) { str.erase(index, 1); removeVowelsRecursive(str, index); } else { removeVowelsRecursive(str, index + 1); } } int main() { string str; cout << "Enter a string: "; getline(cin, str); removeVowelsRecursive(str, 0); cout << "String without vowels: " << str << endl; return 0; }
Output: String without vowels: Prgrmmng
Method 3: Using Pointers
This method uses pointer manipulation to remove vowels.
#include <iostream> #include <string> using namespace std; void removeVowelsPointer(string &str) { string result = ""; for (char *ptr = &str[0]; *ptr; ptr++) { if (string("aeiouAEIOU").find(*ptr) == string::npos) { result += *ptr; } } str = result; cout << "String without vowels: " << str << endl; } int main() { string str; cout << "Enter a string: "; getline(cin, str); removeVowelsPointer(str); return 0; }
Output: String without vowels: Cnt Vwls