0

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Alex
  • 1
  • 1
  • 1
    Does this answer your question? [How to split a String by space](https://stackoverflow.com/questions/7899525/how-to-split-a-string-by-space) – Taylor Apr 29 '22 at 18:35

2 Answers2

0

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
0

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?

David Tejuosho
  • 177
  • 1
  • 14