How to split a string in Java, ignoring multiple consecutive tokens

I am trying to parse the arguments for a command, but if I were to put a few spaces in a string, String.split () would leave empty strings in the result array. Is there any way to get rid of this?

For example: "abc 123".split(" ")leads to {"abc", "", "", "", "", "123"}, but I really want{"abc", "123"}

+5
source share
1 answer

Just use regex

"abc   123".split("\\s+");

Here \sis any space character, and \s+is one or more consecutive space characters.

+16
source

All Articles