Remove Vowels from a String - CPP Solution

1. Introduction

This blog post explores a simple yet interesting string manipulation problem in C++: removing all vowels from a given string. This problem serves as an excellent example to understand string traversal and character comparison in C++.

Problem

The task is to write a function that removes all vowels from a given string. The vowels are 'a', 'e', 'i', 'o', and 'u', and they can appear in both lower and upper cases.

2. Solution Steps

1. Create a new string to store the result.

2. Iterate through each character of the input string.

3. Check if the current character is a vowel (lowercase or uppercase).

4. If it's not a vowel, append it to the result string.

5. Continue this process for all characters in the string.

6. Return the resulting string without vowels.

3. Code Program

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;

// Function to remove vowels from a string
string removeVowels(string s) {
    unordered_set<char> vowels = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
    string result;

    for (char c : s) {
        // Append the character to result if it's not a vowel
        if (vowels.find(c) == vowels.end()) {
            result += c;
        }
    }
    return result;
}

int main() {
    string s = "Hello, World!";
    cout << "String without vowels: " << removeVowels(s) << endl;
    return 0;
}

Output:

String without vowels: Hll, Wrld!

Explanation:

1. The input string "Hello, World!" is processed character by character.

2. Each character is checked against a set of vowels.

3. Non-vowel characters are appended to the result string.

4. The function successfully returns "Hll, Wrld!", which is the input string stripped of all vowels.

5. This example demonstrates basic string manipulation, including character comparison and building a new string based on specific conditions in C++.


Comments