Rin
Rin

Reputation: 324

how to remove blankspace from output java

heloo new here and still learning, im trying to study code from https://www.javatpoint.com/program-to-find-the-duplicate-characters-in-a-string , but i have obstacle on it.

i want to select non-duplicate number on string i could, i got print 4

my input 1 2 3 4 3 2 1

but output is

Duplicate characters 
 
 
 
4
 
 
 
public class DuplicateCharacters {  
     public static void main(String[] args) {  
        String string1 = "1 2 3 4 3 2 1";  
        int count;  
          
        
        char string[] = string1.toCharArray();  
          
        System.out.println("Non-Duplicate characters ");  
        
        for(int i = 0; i <string.length; i++) {  
            count = 1;  
            for(int j = i+1; j <string.length; j++) {  
                if(string[i] == string[j] && string[i] != ' ') {  
                    count++;  
                    string[j] = '0';  
                }  
            }  
           
            if(count == 1 && string[i] != '0')  
                System.out.println(string[i]);  
        }  
    }  
}  

expected output

Duplicate characters 
4

i try to put println out from loop but it get error, sorry for my bad grammar

Upvotes: 1

Views: 102

Answers (1)

GJohannes
GJohannes

Reputation: 1753

Your problem are the blanks in your input. If you don´t want to count those you should simply sanitize your input.

int count;
string1 = string1.replaceAll(" ", "");

char string[] = string1.toCharArray();

I am however a little bit confused what you want achive. Your code returns all non duplicate characters. If you want to get all the duplicate characters you could have a look at my approach for this:

    String input = "1 2 3 4 3 2 1";
    List<Character> countedCharactersAsMoreThanOne = new ArrayList<>();
    input = input.replaceAll(" ","");
    input = input + " ";

    for(int i = 0; i < input.length(); i++){
        Character currentCharacter = input.charAt(i);
        String[] split = input.split(Character.toString(currentCharacter));
        if(split.length > 2 && 
           !countedCharactersAsMoreThanOne.contains(currentCharacter)){
            countedCharactersAsMoreThanOne.add(currentCharacter);
        }
    }

    System.out.println("Number of duplicate characters:");
    System.out.println(countedCharactersAsMoreThanOne.size());
    System.out.println("All duplicated characters");
    System.out.println(countedCharactersAsMoreThanOne);

Upvotes: 1

Related Questions