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

2

6

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)

Norvil answered 5/12, 2010 at 19:39 Comment(0)
C
12

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.

Chatham answered 5/12, 2010 at 19:51 Comment(1)
Note that you can cause trailing empty strings to be included using s.split(",", -1)Scriabin
E
7

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,")
Endurance answered 5/12, 2010 at 19:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.