Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 45: Write a Java program to remove every occurrence of a character in a string.

RemoveDuplicates.java

import java.util.Scanner;

public class RemoveDuplicates
{
	//Method to remove every occurrence of a character in a string.
	public static String removeAllOccurrencesOfChar(String input, char c)
	{
        String str ="";
        for(int i=0; i < input.length();i++)
        {
            if(input.charAt(i)!=c)
            {
                str+=input.charAt(i);
            }
        }
        return str;
	}
	
	//Main method
	public static void main(String[] args)
	{
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the string");
		String input = s.nextLine();

		System.out.println("Enter the character to be removed from the string");
		char c = s.next().charAt(0);
		System.out.println("Changed string");
		System.out.println(RemoveDuplicates.removeAllOccurrencesOfChar(input, c));
	}
}


If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.