How to remove all occurrences of a character from a string
In this shot, we will discuss how to remove all occurrences of a given character from an input string in Java.
For example, let us consider the string “remove some letters”, and the letter to be removed is “e”. Our task is to remove all the “e’s” from the string and return “rmov som lttrs”.
Solution approach
We can use the removeOccurrences() function and pass the input string and the character to be removed as parameters. removeOccurrences() will then return the resultant string.
Method
-
Take a string as input.
-
Take a character that has to be removed from the string as input.
-
We traverse the string, and if the character at that index is not equal to the given character to be removed, then we store those characters into an
arraylist, or, otherwise, continue. -
Now, we convert that
arraylistinto a string and that will be our resultant string.
Code
Let us take a look at the code snippet below.
To run the code, add the string in the first line and the character to remove in the second line. Then press run. Sample input:
remove some letters e
import java.util.ArrayList;import java.util.Scanner;class removeOccurence {public static void main(String[] args) {Scanner scanner=new Scanner(System.in);System.out.println("Enter a string as an input");String input = scanner.nextLine();System.out.println("Enter a letter to be removes from the string");Character character = scanner.next().charAt(0);System.out.println("Our resultant string is: "+removeOccurences(input,character));}private static String removeOccurences(String input, Character character) {ArrayList<Character> al=new ArrayList<>();for(int i=0;i<input.length();i++){char ch = input.charAt(i);if(ch != character){al.add(ch);}}StringBuilder stringBuilder=new StringBuilder();for(char c:al){stringBuilder.append(c);}return stringBuilder.toString();}}
Enter the input below
Explanation
-
In line 1, we import the
java.util.ArrayListclass. -
In line 2, we import the
java.util.Scannerclass to read input from the user. -
In line 8, inside the
mainfunction, we create aScannerobject to take the input string from the user and store that input in aString. -
In line 10, we create a
Scannerobject to take the input character from the user and store that input in aCharacter. -
In line 12, we call the
removeOccurences()function which will remove the occurrences and return the resultant string. -
In lines 15 to 31, we define the
removeOccurences()function. In this function, we initiate an emptyArrayList, and traverse the input string. Whenever we get the character at that particular index not equal to the character passed by the user that has to be removed, we add those characters toArraylist. -
In lines 26 to 31, we again traverse
ArrayListand add all characters to trace up our resultant string, which we return and print.
In this way, we can remove all occurrences of a given character from an input string in Java.