Open In App
Related Articles

Remove all occurrences of a character in a string

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Given a string. Write a program to remove all the occurrences of a 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"

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

Implementation:

C++

// C++ program to remove a particular character
// from a string.
#include <bits/stdc++.h>
using namespace std;
 
void removeChar(char* s, char c)
{
 
    int j, n = strlen(s);
    for (int i = j = 0; i < n; i++)
        if (s[i] != c)
            s[j++] = s[i];
 
    s[j] = '\0';
}
 
int main()
{
    char s[] = "geeksforgeeks";
    removeChar(s, 'g');
    cout << s;
    return 0;
}

                    

Java

// Java program to remove
// a particular character
// from a string.
class GFG
{
static void removeChar(String s, char c)
{
    int j, count = 0, n = s.length();
    char []t = s.toCharArray();
    for (int i = j = 0; i < n; i++)
    {
        if (t[i] != c)
        t[j++] = t[i];
        else
            count++;
    }
     
    while(count > 0)
    {
        t[j++] = '\0';
        count--;
    }
     
    System.out.println(t);
}
 
// Driver Code
public static void main(String[] args)
{
    String s = "geeksforgeeks";
    removeChar(s, 'g');
}
}
 
// This code is contributed
// by ChitraNayal

                    

Python3

# Python3 program to remove
# a particular character
# from a string.
 
# function for removing the
# occurrence of character
def removeChar(s, c) :
     
    # find total no. of
    # occurrence of character
    counts = s.count(c)
 
    # convert into list
    # of characters
    s = list(s)
 
    # keep looping until
    # counts become 0
    while counts :
         
        # remove character
        # from the list
        s.remove(c)
 
        # decremented by one
        counts -= 1
 
    # join all remaining characters
    # of the list with empty string
    s = '' . join(s)
     
    print(s)
 
# Driver code
if __name__ == '__main__' :
     
    s = "geeksforgeeks"
    removeChar(s,'g')
     
# This code is contributed
# by Ankit Rai

                    

C#

// C# program to remove a
// particular character
// from a string.
using System;
 
class GFG
{
static void removeChar(string s,
                       char c)
{
    int j, count = 0, n = s.Length;
    char[] t = s.ToCharArray();
    for (int i = j = 0; i < n; i++)
    {
        if (s[i] != c)
        t[j++] = s[i];
        else
            count++;
    }
     
    while(count > 0)
    {
        t[j++] = '\0';
        count--;
    }
     
    Console.Write(t);
}
 
// Driver Code
public static void Main()
{
    string s = "geeksforgeeks";
    removeChar(s, 'g');
}
}
 
// This code is contributed
// by ChitraNayal

                    

Javascript

<script>
 
// Javascript program to remove
// a particular character
// from a string.
function removeChar(s, c)
{
    let j, count = 0, n = s.length;
    let t = s.split("");
     
    for(let i = j = 0; i < n; i++)
    {
        if (t[i] != c)
            t[j++] = t[i];
        else
            count++;
    }
      
    while (count > 0)
    {
        t[j++] = '\0';
        count--;
    }
    document.write(t.join(""));
}
 
// Driver Code
let s = "geeksforgeeks";
removeChar(s, 'g');
 
// This code is contributed by avanitrachhadiya2155
 
</script>

                    

PHP

<?php
// PHP program to remove a
// particular character
// from a string.
 
function removeChar($s, $c)
{
 
    $n = strlen($s);
    $count = 0;
    for ($i = $j = 0; $i < $n; $i++)
    {
    if ($s[$i] != $c)
        $s[$j++] = $s[$i];
    else
        $count++;
    }
    while($count--)
    {
        $s[$j++] = NULL;
    }
    echo $s;
}
 
// Driver code
$s = "geeksforgeeks";
removeChar($s, 'g');
 
// This code is contributed
// by ChitraNayal
?>

                    

Output
eeksforeeks

Complexity Analysis:

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

Second Approach in C++:  We can also use the STL string class and erase function to delete any character at any position using the base addressing (string.begin()).

Implementation:

C++14

#include <bits/stdc++.h>
using namespace std;
 
string removechar(string& word,char& ch)
{
    for(int i=0;i<word.length();i++)
    {
        if(word[i]==ch){
        word.erase(word.begin()+i);
        i--;
        }
    }
     
    return word;
}
 
 
// driver's code
int main()
{
    string word="geeksforgeeks";
    char ch='e';
    cout<<removechar(word,ch);
 
    return 0;
}

                    

Java

// Java code
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));
    }
}
 
// This code is contributed by Samim Hossain Mondal.

                    

Python3

# Python3 code for above approach
def removechar(word, ch):
    i = 0
    while(i < len(word)):
     
        if(word[i] == ch):
            word = word[:i] + word[i+1:]
            i -= 1
        i += 1
     
    return word
 
# driver's code
word="geeksforgeeks"
ch='e'
print(removechar(word,ch))
 
# This code is contributed by Akshay Tripathi

                    

C#

// C# code
using System;
using System.Text;
using System.Collections;
 
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[i] == ch) {
                s.Remove(i, 1);
                i--;
            }
        }
        return s.ToString();
    }
 
    // driver's code
    public static void Main()
    {
        string word = "geeksforgeeks";
        char ch = 'e';
        Console.WriteLine(removechar(word, ch));
    }
}
 
// This code is contributed by Samim Hossain Mondal.

                    

Javascript

function removechar(word, ch)
{
    let ans="";
    for(let i=0;i<word.length;i++)
    {
        if(word[i]!=ch){
            ans+=word[i];
        }
    }
     
    return ans;
}
 
 
// driver's code
    let word="geeksforgeeks";
    let ch='e';
    document.write(removechar(word,ch));

                    

Output
gksforgks

Complexity Analysis:

  • Time Complexity: O(n^2), where n is length of input string. and erase function will also take O(n) time in worst case.
  • Auxiliary Space: O(1).

Third approach : Using built-in replace() function in Python and Javascript.

Implementation:

C++

#include <iostream>
#include <string>
 
using namespace std;
 
// function for removing the occurrence of character using replace() function
void removeChar(string& word, char ch) {
    size_t found = word.find(ch);
    while (found != string::npos) {  // loop until no more occurrences of ch found
        word.erase(found, 1);        // remove character at position found
        found = word.find(ch, found); // search for the next occurrence of ch
    }
    cout << word << endl;
}
 
// Driver code
int main() {
    string word = "geeksforgeeks";
    removeChar(word, 'k');
    return 0;
}

                    

Java

public class Main {
    // function for removing the occurrence of character using replace() function
    public static void removeChar(String word, char ch) {
        word = word.replace(Character.toString(ch), "");
        System.out.println(word);
    }
 
    // Driver code
    public static void main(String[] args) {
        String word = "geeksforgeeks";
        removeChar(word, 'k');
    }
}
// code by ksam24000

                    

Python3

# Python3 program to remove a particular character
 
# function for removing the
# occurrence of character using replace() function
def removeChar(word, ch) :
  word = word.replace(ch,'')
  print(word)
 
# Driver code
if __name__ == '__main__' :
   
  word = "geeksforgeeks"
  removeChar(word,'k')
 
# This Code is contributed by Pratik Gupta

                    

C#

using System;
 
class Program {
    // function for removing the
    // occurrence of character using replace() function
    static void removeChar(string word, char ch)
    {
        word = word.Replace(ch.ToString(), "");
        Console.WriteLine(word);
    }
 
    // Driver code
    static void Main(string[] args)
    {
        string word = "geeksforgeeks";
        removeChar(word, 'k');
    }
}

                    

Javascript

// Javascript program to remove a particular character
var word = "geeksforgeeks";
 
// '/g/' to find the character globally and replace them with empty parameter
var c =/k/g ;
word = word.replace(c, '');
console.log(word);

                    

Output
geesforgees

Complexity Analysis:

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

Fourth Approach: Using Recursion

Here our recursive function’s base case will be when string length’s become 0. And in the recursive function, if the encountered character is the character that we have to remove then call the recursive function from the next character else store this character in answer and then call the recursive function from the next character.

Code:

C++

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to remove all occurrences
// of a character in the string
string removeChar(string str, char ch)
{
    // Base Case
    if (str.length() == 0) {
        return "";
    }
 
    // Check the first character
    // of the given string
    if (str[0] == ch) {
 
        // Pass the rest of the string
        // to recursion Function call
        return removeChar(str.substr(1), ch);
    }
 
    // Add the first character of str
    // and string from recursion
    return str[0] + removeChar(str.substr(1), ch);
}
 
// Driver Code
int main()
{
    // Given String
    string str = "geeksforgeeks";
 
    // Function Call
    str = removeChar(str, 'g');
    cout << str;
    return 0;
}

                    

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class Main {
    // Function to remove all occurrences
    // of a character in the string
    static String removeChar(String str, char ch)
    {
        // Base Case
        if (str.length() == 0) {
            return "";
        }
 
        // Check the first character
        // of the given string
        if (str.charAt(0) == ch) {
 
            // Pass the rest of the string
            // to recursion Function call
            return removeChar(str.substring(1), ch);
        }
 
        // Add the first character of str
        // and string from recursion
        return str.charAt(0)
            + removeChar(str.substring(1), ch);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        // Given String
        String str = "geeksforgeeks";
 
        // Function Call
        str = removeChar(str, 'g');
        System.out.println(str);
    }
}

                    

Python3

# Function to remove all occurrences
# of a character in the string
 
 
def removeChar(str, ch):
    # Base Case
    if len(str) == 0:
        return ""
 
    # Check the first character
    # of the given string
    if str[0] == ch:
 
        # Pass the rest of the string
        # to recursion Function call
        return removeChar(str[1:], ch)
 
    # Add the first character of str
    # and string from recursion
    return str[0] + removeChar(str[1:], ch)
 
 
# Driver Code
if __name__ == '__main__':
    # Given String
    str = "geeksforgeeks"
 
    # Function Call
    str = removeChar(str, 'g')
    print(str)

                    

C#

using System;
 
class MainClass {
    // Function to remove all occurrences
    // of a character in the string
    public static string RemoveChar(string str, char ch)
    {
        // Base Case
        if (str.Length == 0) {
            return "";
        }
 
        // Check the first character
        // of the given string
        if (str[0] == ch) {
            // Pass the rest of the string
            // to recursion Function call
            return RemoveChar(str.Substring(1), ch);
        }
 
        // Add the first character of str
        // and string from recursion
        return str[0] + RemoveChar(str.Substring(1), ch);
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        // Given String
        string str = "geeksforgeeks";
 
        // Function Call
        str = RemoveChar(str, 'g');
        Console.WriteLine(str);
    }
}

                    

Javascript

function removeChar(str, ch) {
  // Base Case
  if (str.length == 0) {
    return "";
  }
 
  // Check the first character
  // of the given string
  if (str[0] == ch) {
    // Pass the rest of the string
    // to recursion Function call
    return removeChar(str.slice(1), ch);
  }
 
  // Add the first character of str
  // and string from recursion
  return str[0] + removeChar(str.slice(1), ch);
}
 
// Driver Code
let str = "geeksforgeeks";
str = removeChar(str, 'g');
console.log(str);

                    

Output
eeksforeeks

Complexity Analysis-

  • Time Complexity: O(n), where n is the length of the input string. 
  • Auxiliary Space: O(n),if we consider recursion stack space


Last Updated : 20 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads