Possible Duplicate:
How do I split a string with any whitespace chars as delimiters?
Both of these Python lines gives me exactly the same list:
print("1 2 3".split())
print("1 2 3".split())
Output:
['1', '2', '3']
['1', '2', '3']
I was surprised when the Java 'equivalents' refused:
System.out.println(Arrays.asList("1 2 3".split(" ")));
System.out.println(Arrays.asList("1 2 3".split(" ")));
Output:
[1, 2, 3]
[1, , 2, , , 3]
How do I make Java ignore the number of spaces?
Try this:
"1 2 3".split(" +")
// original code, modified:
System.out.println(Arrays.asList("1 2 3".split(" +")));
System.out.println(Arrays.asList("1 2 3".split(" +")));
The argument passed to split()
is a Regex, so you can specify that you allow the separator to be one or more spaces.
I you also allow tabs and other white-space characters as separator, use "\s":
"1 2 3".split("\\s+")
And if you expect to have trailing or heading whitespaces like in " 1 2 3 "
, use this:
" 1 2 3 ".replaceAll("(^\\s+|\\s+$)", "").split("\\s+")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With