Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should ",7-6-5-4-3-2-1,".split(',') return?

What should ",7-6-5-4-3-2-1,".split(',') return?

It seems to return

  blank string
  7-6-5-4-3-2-1

ie. two strings. I'd expect either one or three strings - that is a blank string at both ends or just the string between ','s.

Am I wrong? Is there a good explanation for the current behaviour?

EDIT:

OK. So yes, I had the wrong expectation and no, there is no good explanation other than Java works that way :). Thanks.

EDIT2:

You can get the desired behaviour with split(",", -1) (Scala 2.8.1)

like image 267
The Archetypal Paul Avatar asked Dec 05 '10 19:12

The Archetypal Paul


2 Answers

This is how it works. See here, which explains Java's regex version of it, but it's the same thing in the end:

Trailing empty strings are therefore not included in the resulting array.

like image 131
Daniel C. Sobral Avatar answered Oct 21 '22 04:10

Daniel C. Sobral


The behaviour is expecteded. String#split(Char) ultimately (via StringLike#split(Char) and String#split(String)) calls the Java String#split(String, 0) which is documented:

[...] the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded

Edit - If you want more control over splitting strings, look at Splitter in the Guava libraries.

Splitter.on(',').split(",7-6-5-4-3-2-1,")
like image 24
Ben Lings Avatar answered Oct 21 '22 05:10

Ben Lings