Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make Java ignore the number of spaces in a string when splitting? [duplicate]

Tags:

java

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?

like image 327
tshepang Avatar asked Feb 01 '11 11:02

tshepang


1 Answers

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+")
like image 153
Arnaud Le Blanc Avatar answered Nov 09 '22 17:11

Arnaud Le Blanc