Open In App

Remove all occurrences of a character in a string

Last Updated : 17 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string and a character, remove all the occurrences of the character in the string.

Examples: 

Input : s = “geeksforgeeks”
c = ‘e’
Output : s = “gksforgks”

Input : s = “geeksforgeeks”
c = ‘g’
Output : s = “eeksforeeks”

Input : s = “geeksforgeeks”
c = ‘k’
Output : s = “geesforgees”

Using Built-In Methods

C++
#include <algorithm>
#include <iostream>
using namespace std;

int main() {
    string s = "ababca";
    char c = 'a';
  
    // Remove all occurrences of 'c' from 's'
    s.erase(remove(s.begin(), s.end(), c), s.end());

    cout << s;
    return 0;
}
Java
import java.util.*;

public class Main {
    public static void main(String[] args) {
        String s = "ababca";
        char c = 'a';
        
        // Remove all occurrences of 'c' from 's'
        s = s.replace(String.valueOf(c), "");

        System.out.println(s);
    }
}
Python
s = "ababca"
c = 'a'

# Remove all occurrences of 'c' from 's'
s = s.replace(c, '')

print(s)
C#
using System;

class Program {
    static void Main() {
        string s = "ababca";
        char c = 'a';

        // Remove all occurrences of 'c' from 's'
        s = s.Replace(c.ToString(), "");

        Console.WriteLine(s);
    }
}
JavaScript
let s = "ababca";
let c = 'a';

// Remove all occurrences of 'c' from 's'
s = s.split(c).join('');

console.log(s);

Output
bbc


Writing Your Own Method

The idea is to maintain an index of the resultant string.  

C++
#include <iostream>
using namespace std;

void removeChar(string &s, char c) {

    int j = 0;
    for (int i = 0; i < s.size(); i++) {
        if (s[i] != c) {
            s[j++] = s[i]; 
        }
    }
  
    // Resize string to remove the 
    // extra characters
    s.resize(j);  
}

int main() {
    string s = "geeksforgeeks";
    removeChar(s, 'g');
    cout << s;
    return 0;
}
Java
import java.util.*;
public class GFG {

    public static String removechar(String word, char ch)
    {
        StringBuilder s = new StringBuilder(word);
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ch) {
                s.deleteCharAt(i);
                i--;
            }
        }

        return s.toString();
    }

    // driver's code
    public static void main(String args[])
    {
        String word = "geeksforgeeks";
        char ch = 'e';
        System.out.println(removechar(word, ch));
    }
}

Output
eeksforeeks

Time Complexity : O(n) where n is length of input string.
Auxiliary Space : O(1)



Next Article
Article Tags :
Practice Tags :

Similar Reads