Program to Remove Duplicate Characters from a Word
Java program to input a word and remove the duplicate characters present in it.
Question:
Write a program to input a word from the user and remove the duplicate characters present in it.
Example:
INPUT - abcabcabc OUTPUT - abc
INPUT - javaforschool OUTPUT - javforschl
INPUT - Mississippi OUTPUT - Misp
Programming Code:
Java
/**
* The class RemoveDupChar inputs a word and removes duplicate characters
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/
import java.util.Scanner;
class RemoveDupChar
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter any word : ");
String s = sc.nextLine();
int l = s.length();
char ch;
String ans="";
for(int i=0; i<l; i++)
{
ch = s.charAt(i);
if(ch!=' ')
ans = ans + ch;
s = s.replace(ch,' '); //Replacing all occurrence of the current character by a space
}
System.out.println("Word after removing duplicate characters : " + ans);
}
}Output:
Example 1: Enter any word : Mississippi Word after removing duplicate characters : Misp
Example 2: Enter any word : Attitude Word after removing duplicate characters : Atiude