Home > Enterprise >  I want to split a string with multiple whitespaces using split() method?
I want to split a string with multiple whitespaces using split() method?

Time:04-30

This program is to return the readable string for the given morse code.

class MorseCode{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String morseCode = scanner.nextLine();
        System.out.println(getMorse(morseCode));
    }
    private static String getMorse(String morseCode){
        StringBuilder res = new StringBuilder();
        String characters = new String(morseCode);
        String[] charactersArray = characters.split("   "); /*this method isn't 
                                                              working for 
                                                              splitting what 
                                                              should I do*/
        for(String charac : charactersArray)
            res.append(get(charac)); /*this will return a string for the 
                                       corresponding string and it will 
                                       appended*/
        return res.toString();
    }

Can you people suggest a way to split up the string with multiple whitespaces. And can you give me some example for some other split operations.

CodePudding user response:

Could you please share here the example of source string and the result? Sharing this will help to understand the root cause.

By the way this code just works fine

String source = "a    b    c    d";
String[] result = source.split("    ");
for (String s : result) {
    System.out.println(s);
}

The code above prints out:

a
b
c
d

CodePudding user response:

First, that method will only work if you have a specific number of spaces that you want to split by. You must also make sure that the argument on the split method is equal to the number of spaces you want to split by.
If, however, you want to split by any number of spaces, a smart way to do that would be trimming the string first (that removes all trailing whitespace), and then splitting by a single space:

charactersArray = characters.trim().split(" ");

Also, I don't understand the point of creating the characters string. Strings are immutable so there's nothing wrong with doing String characters = morseCode. Even then, I don't see the point of the new string. Why not just name your parameter characters and be done with it?

  • Related