Tuesday, 27 October 2015

Java program to remove duplicate characters or repeated character from a given string.

Example: Thiiis is aa tessstt ssstring
OUTPUT:  This is a test string

hus our motive is to remove repeated characters or duplicate characters from a given string. This is done by following concept.
Step #1: select the starting character:   ch=str.charAt(0);    (hhhello)
Step #2: Add the character to the resulting/output String: ans = ans + ch;
Step #3: Now until the same character appears skip to add the character in the output string:
while( s.charAt(++i)==ch)
Step #4: Do this uptil i < l ; means for whole length of string.

// Java program to remove duplicate/repeated characters from a string  
import java.util.*;
class RemoveDuplicate
{
    public static void main(String args[])
    {
String s,ans="";
char ch ;
int l,i=0;
Scanner sc=new Scanner(System.in);
        System.out.print("Enter any string: "); // Inputting the word
        s = sc.nextLine();
l=s.length();
s+=" "; // *Adding extra space at the end because last character is compared with something else index out of bound error.
ch=s.charAt(0); // taking ch as first character
while(i<l)
{
ans= ans+ ch;  // adding each individual character to the answer string or output string without repeated characters
 
while(s.charAt(++i)==ch && i<l)
{}
ch=s.charAt(i); // **to store the previously last character in ch
}
 
System.out.println("String after removing repeated characters : \n"+ans); // Printing the string without duplicate characters
}
    }

No comments:

Post a Comment