Skip to content
Related Articles

Related Articles

Improve Article

Remove all occurrences of a character from a string using STL

  • Last Updated : 12 Jan, 2021

Given a string S and a character C, the task is to remove all the occurrences of the character C from the given string.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input:vS = “GFG IS FUN”, C = ‘F’
Output:GG IS UN
Explanation:
Removing all occurrences of the character ‘F’ modifies S to “GG IS UN”.
Therefore, the required output is GG IS UN



Input: S = “PLEASE REMOVE THE SPACES”, C = ‘ ‘
Output: PLEASEREMOVETHESPACES
Explanation:
Removing all occurrences of the character ‘ ‘ modifies S to “GG IS UN”.

Approach: The idea is to use erase() method and remove() function from C++ STL. Below is the syntax to remove all the occurrences of a character from a string.

S.erase(remove(S.begin(), S.end(), c), S.end())

Below is the implementation of the above approach:

C++




// C++ program of the above approach
#include <algorithm>
#include <iostream>
using namespace std;
  
// Function to remove all occurences
// of C from the string S
string removeCharacters(string S, char c)
{
  
    S.erase(remove(
                S.begin(), S.end(), c),
            S.end());
  
    return S;
}
  
// Driver Code
int main()
{
  
    // Given String
    string S = "GFG is Fun";
    char C = 'F';
    cout << "String Before: " << S << endl;
  
    // Function call
    S = removeCharacters(S, C);
  
    cout << "String After: " << S << endl;
    return 0;
}
Output:
String Before: GFG is Fun
String After: GG is un

Time Complexity: O(N2)
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :