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:
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”:
And if you expect to have trailing or heading whitespaces like in
" 1 2 3 ", use this: