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”.
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.
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 arraylist
into a string and that will be our resultant string.
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
In line 1, we import the java.util.ArrayList
class.
In line 2, we import the java.util.Scanner
class to read input from the user.
In line 8, inside the main
function, we create a Scanner
object to take the input string from the user and store that input in a String
.
In line 10, we create a Scanner
object to take the input character from the user and store that input in a Character
.
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 empty ArrayList
, 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 to Arraylist
.
In lines 26 to 31, we again traverse ArrayList
and 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.