9

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?

Community
  • 1
  • 1
tshepang
  • 12,111
  • 21
  • 91
  • 136

4 Answers4

26

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+")
Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194
4

How about using a neat regular expression? Note that according to Java API documentation, String.split will take a regular expression string parameter.

"1 2   3".split("\\s+")
Uszui
  • 51
  • 2
3

I think this should do:

yourString.trim().split("\\s+");
Costi Ciudatu
  • 37,042
  • 7
  • 56
  • 92
1

I prefer "1 2 3".split("\s+") than "1 2 3".split(" +"). When you use \s instead of " " it is more readable and safer.

AlexR
  • 114,158
  • 16
  • 130
  • 208