regex – Remove vowels from string C++

regex – Remove vowels from string C++

The canonical way to remove elements from a sequential containers according to a predicate (a condition) is to use std::remove_if. Unlike its name implies, this standard algorithm doesnt quite remove the elements, it moves them to the back of the container so they are easy to erase, leaving the other elements intact and in the same order. It returns an iterator that indicates the beginning of the portion of the container which contains the removed elements. Since the standard algorithms cannot change the size the containers they operate on, these elements must then be removed using the containers appropriate remove method. In the case of std::string, thats std::string::erase.

std::remove_if accepts a pair of iterators which define the range of elements to inspect, as well as a predicate that is used to determine which elements to remove. Elements for which the predicate is true are removed.

#include <algorithm>
#include <iostream>
#include <string>

// Returns true if p_char is a vowel
bool is_vowel(const char p_char)

    constexpr char vowels[] = { a, e, i, o, u, A, E, I, O, U };
    return std::find(std::begin(vowels), std::end(vowels), p_char) != std::end(vowels);

std::string remove_vowel(std::string st) 
    // Moves all the characters for which `is_vowel` is true to the back
    //  and returns an iterator to the first such character
    auto to_erase = std::remove_if(st.begin(), st.end(), is_vowel);

    // Actually remove the unwanted characters from the string
    st.erase(to_erase, st.end());
    return st;

int main()
    std::cout << remove_vowel(Hello, World!);

is not a valid character, you cannot place an empty one (such thing does not exist in C++) into the string to remove content…

What you can do is moving the non-vowels, i. e. the consonants, to front, skipping the vowels, and afterwards erase the surplus characters at the end:

auto pos = st.begin();
for(auto c : st)
        *pos++ = c;
st.erase(pos, st.end());

Edit: As François (correctly) denotes: There is no need to re-invent the wheel (provided you are not disallowed to use the standard library):

st.erase(std::remove_if(st.begin(), st.end(), [](char c) { return isConsonant(c); }), st.end());

Be aware that std::remove_if (as well as std::remove) remove by just moving the elements to remain to front and returns an iterator to the new end of data – but does not really remove the elements behind the new end. So it is necessary to explicitly erase them as shown above.

regex – Remove vowels from string C++

Leave a Reply

Your email address will not be published. Required fields are marked *