开发者

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

开发者 https://www.devze.com 2023-01-28 06:32 出处:网络
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 str开发者_开发知识库ings - that is a blank stri

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 str开发者_开发知识库ings - 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)


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.


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,")
0

精彩评论

暂无评论...
验证码 换一张
取 消