Remove all occurrences of a character from a string using STL Last Updated : 23 Jul, 2025 Comments Improve Suggest changes 14 Likes Like Report 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: 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 occurrences // 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) Comment R rohit5swd Follow 14 Improve R rohit5swd Follow 14 Improve Article Tags : Strings DSA STL cpp-strings-library Explore DSA FundamentalsLogic Building Problems 2 min read Analysis of Algorithms 1 min read Data StructuresArray Data Structure 3 min read String in Data Structure 2 min read Hashing in Data Structure 2 min read Linked List Data Structure 2 min read Stack Data Structure 2 min read Queue Data Structure 2 min read Tree Data Structure 2 min read Graph Data Structure 3 min read Trie Data Structure 15+ min read AlgorithmsSearching Algorithms 2 min read Sorting Algorithms 3 min read Introduction to Recursion 15 min read Greedy Algorithms 3 min read Graph Algorithms 3 min read Dynamic Programming or DP 3 min read Bitwise Algorithms 4 min read AdvancedSegment Tree 2 min read Binary Indexed Tree or Fenwick Tree 15 min read Square Root (Sqrt) Decomposition Algorithm 15+ min read Binary Lifting 15+ min read Geometry 2 min read Interview PreparationInterview Corner 3 min read GfG160 3 min read Practice ProblemGeeksforGeeks Practice - Leading Online Coding Platform 6 min read Problem of The Day - Develop the Habit of Coding 5 min read Like