Remove certain characters from a String in C++

In this article, we will learn how to remove certain characters from a string in C++.

Table Of Contents

Problem Description

Suppose we have a string sampleStr, and an array of characters arr. Now we want to remove all those characters from string that exists in array. For example, if our string, and char array is like this,

string sampleStr = "abcdaabbccddaca";

char arr[] = {'a', 'c'};

Then code should remove all occurrences of ‘a’ and ‘c’ from the string. Modified string should be like,

bdbbdd

There are two method to remove certain character from a string in C++. Let’s discuss them one by one.

Advertisements

Method 1: Using while loop

Iterate over all characters in string using a while loop, and iterators. During iteration, for each character of string, check if it matches any character from array using the STL algorithm any_of(). If yes, then remove those characters from the string. For example,

#include <iostream>
#include <algorithm>

using namespace std;

int main()

{
    string sampleStr = "abcdaabbccddaca";

    char arr[] = {'a', 'c'};

    // Get iterator pointing to first character in string
    auto it = sampleStr.begin();

    // Iterate over all characters in string sampleStr
    while( it != sampleStr.end())
    {
        // If any character from string matches with characters in array arr
        // then remove that character from string
        if (std::any_of(
                std::begin(arr),
                std::end(arr),
                [&](const char& ch){return (*it) == ch;}))
        {
            // Remove character from string
            it = sampleStr.erase(it);
        }
        else
        {
            it++;
        }
    }

    cout << "Modified String : " << sampleStr << endl;

    return 0;
}

Output

Modified String : bdbbdd

It removed all the characters in string, that matches with any character in array.

Method 2: Using STL function for_each(), erase() and remove()

In this method, we use STL functions to remove certain character from a string in C++. We will use following STL Algorithms,

  • for_each()
  • erase()
  • remove()

We will iterate over all characters in array using, a for_each() function. During iteration, we will apply a lambda function on each character of array. Inside this lambda function, we will remove all the occurrences of characters of array from the string. Let’s see the example,

#include <iostream>
#include <algorithm>

int main()

{
    std::string sampleStr = "abcdaabbccddaca";

    char arr[] = {'a', 'c'};

    // Remove all characters of array "arr" 
    // from string "sampleStr"
    std::for_each(
        std::begin(arr),
        std::end(arr),
        [&](const char& ch)
        {
            // Remove char ch from string
            sampleStr.erase(
                        remove(
                            sampleStr.begin(),
                            sampleStr.end(),
                            ch),
                        sampleStr.end());
        });

    std::cout << sampleStr << std::endl;

    return 0;
}

Output

bdbbdd

It removed all the occurrences of characters ‘a’, and ‘c’ from the string.

Special Notes about remove() and erase()

The remove() function

  • The remove() function simply moved up the elements in the sequence, it overwrites the values that we wanted to remove. So basically the values we wanted to remove are gone.
    • Let take an example I have a vector with values {6,7,8,9,10}. After that I call remove() for val = 8, the vector now has {6,7,9,10,10}. That is, 9 and 10 got moved up so that 8 is gone from the vector but the size of vector hasn’t changed. Also, the end of the vector now contains additional left over copy of 10.
    • Same thing we can also think with a string let’s say I have a string s = “abcd” and I call remove() function for removing ‘a’ then s will be “bcdd”. One extra copy of d will come in the end
    • Now we have extra part in the string (also in vector) so we have to remove it. Here erase() function come in the picture. It removes that extra part.
    • The remove() operation actually does not change the size of container and does not frees up the memory.

The erase() functions

  • Now erase() function will takes two iterators as arguments. First that string iterator which came from the remove() function and second end part (where to end). and It will remove those extra copy which added unnecessary.
    • Let’s take an example str = "abcd" and we have to remove ‘a’
    • So first auto removedpart = remove(str.begin(),str.end(),'a')
    • now removedpart contain an iterator pointing to logical end of string “bcdd” i.e. second last d. Now we have to remove one extra d from this. So we will use erase() function
    • str.erase(removedpart,str.end());
    • now this ‘d’ extra copy will remove from the end

The combination of std::remove() and std::erase() allows you to remove matching elements from the container. By shifting the elements at the end and then truncate them. This is also called remove-erase idiom in C++.

Summary

We have seen two different methods to remove certain characters from a string. One is the naive solution which has time complexity O(n*m). Here, n is the size of string and m is the size of removing array. Then another method we used the STL function to avoid lengthy code. Internally it also takes O(n) time. Despite the fact that every method has the same complexity and space complexity, STL function allows us to avoid writing lengthy code.

In this chapter, we also saw the workings of the erase() and remove() functions, and we learned that remove() does not free memory but erase() does. Thanks.

Advertisements

Thanks for reading.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top