Skip to content
Advertisement

Remove duplicate letters from a string sentence while keeping the spaces from the sentence

I am trying to take a sentence that a user has entered into a String variable and remove the duplicate letters while keeping the spaces in the sentence. For example if a user enters “hello my name is danny” it will return “Helo my nam is dn”.

To do this I have already tried this code:

package noRepeats.java;

import java.util.Scanner;

public class NoRepeats {

    public static void main(String[] args) {
        
        System.out.println("Please enter a sentence:");
    
        Scanner sc = new Scanner(System.in);
        String userInput = sc.nextLine();
    
        String sentence = userInput;
        
        char[] Array = sentence.toCharArray();
        
        StringBuilder sb3 = new StringBuilder();
        for(int i=0; i<Array.length;i++) {
            boolean repeated = false;
            for(int j = i + 1; j<Array.length;j++) {
                if(Array[i]==Array[j]) {
                     repeated = true;
                     break;
                }
            }
            if(!repeated) {
                sb3.append(Array[i]);
            }
        }
        System.out.println(sb3);
    }
}

This code however doesn’t keep the spaces of the sentence and it also seems to remove the first letter in a duplicate pair but not the second.

Advertisement

Answer

The logic you are using to check the repeated is slightly incorrect. You need to check if the current character that you are looping is present in the string builder that you have built so far till that point. This way a character will be allowed the first time and not the second time. For the space thing, it is just a simple condition that you can add.

for (int i = 0; i < array.length; i++) {
    if(array[i] == ' ') {
        sb3.append(array[i]);
        continue;
    }
    boolean repeated = sb3.indexOf(String.valueOf(array[i])) >= 0;
    if (!repeated) {
        sb3.append(array[i]);
    }
}

Also, I wanted to point that you should not start your variable name with a Capital letter, so the variable Array should be array.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement