JavaPilgrim
JavaPilgrim

Reputation: 77

Trying to print each character in the entered word only once in Java

This is what I have so far:

   import java.util.*;
class kl {
    public static void main(){        
        StringBuffer sbuffer = new StringBuffer();
       Scanner input = new Scanner(System.in);
       System.out.println("Enter a string");
        sbuffer.append(input.nextLine());
        int j;
        for(int i=0; i<sbuffer.length()-1; i++){
            for(j=0; j<sbuffer.length()-1; j++){
                if(i==j)
                 continue;
                else if (sbuffer.charAt(i)==(sbuffer.charAt(j)))
                 sbuffer.deleteCharAt(i);
                }
            }
            System.out.println(sbuffer);
    }
}

For example, if the user enters: "Mom", the output should be "mo" (case doesn't matter). What does matter is the sequence in which the characters appear, therefore "om" is not what I seek. The code above works, but the output isn't right. I've thought a lot about it, but been unable to figure out what's wrong. Any help is appreciated, Thanks.

Upvotes: 1

Views: 92

Answers (2)

Darshan Patel
Darshan Patel

Reputation: 2899

Another way to do it,

String str = "Mom";

Set<Character> set = new LinkedHashSet();
for (int i = 0; i < str.length(); i++) {
    set.add(Character.toLowerCase(str.charAt(i)));
}

StringBuilder sb = new StringBuilder();
for (Character character : set) {
    sb.append(character);
}
System.out.println("Output : "+sb.toString());

Upvotes: 1

Eran
Eran

Reputation: 393946

Your comparison is case sensitive, since 'M' != 'm'.

To make a case insensitive comparison, you can (for example) change them both to lower case :

else if (Character.toLowerCase(sbuffer.charAt(i))==Character.toLowerCase(sbuffer.charAt(j)))

And if you wish to keep the character with the lower index, change

sbuffer.deleteCharAt(i);

to

sbuffer.deleteCharAt(j);
j--; // this is important, since after removing a character, the following
     // characters are shifted to the left

Oh, one more thing, you are skipping the last character. Change your loop to :

    for(int i=0; i<sbuffer.length(); i++){
        for(j=i+1; j<sbuffer.length(); j++){

To summarize :

    for(int i=0; i<sbuffer.length(); i++){
        for(j=i+1; j<sbuffer.length(); j++){
            if (Character.toLowerCase(sbuffer.charAt(i))==Character.toLowerCase(sbuffer.charAt(j))) {
                sbuffer.deleteCharAt(j);
                j--;
            }
        }
    }
    System.out.println(sbuffer);

Upvotes: 1

Related Questions