1

Can someone explain this behaviour:

"one,two,three".split(",").length == 3
"one,two".split(",").length == 2
"one".split(",").length == 1
"".split(",").length != 0 // eek!
pirho
  • 11,565
  • 12
  • 43
  • 70
DodgyCodeException
  • 5,963
  • 3
  • 21
  • 42
  • 1
    What exactly? That splitting an empty string will not produce an empty array? – luk2302 Oct 24 '17 at 16:54
  • 5
    Why are you surprised by line 4 but not line 3? Both input strings lack a comma. – azurefrog Oct 24 '17 at 16:54
  • The `split` method splits the string into tokens which are separated by a comma. The third line contains one token. There it returns a one-element array. The fourth line contains no tokens. So why doesn't it return a zero-element array? – DodgyCodeException Oct 24 '17 at 16:56
  • 1
    It doesn't contain no tokens, it contains one token, which is the literal string `""`. – azurefrog Oct 24 '17 at 16:57
  • why? Because it does! – luk2302 Oct 24 '17 at 16:57
  • @luk2302 it does *not* produce an empty array. It produces a one-element array. – DodgyCodeException Oct 24 '17 at 16:57
  • check out [this](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) post, it may help – Gor Oct 24 '17 at 16:57
  • man I am getting tired of ppl downvoting perfectly fair questions. it's disrespectful. stop it! aaaaand happy again :) – Jack Flamp Oct 24 '17 at 16:59
  • 3
    @JackFlamp since this is described in the Javadoc of the `String.split` method, this is a basic example of "does not show research effort". Not that I downvoted, mind you. – Andy Turner Oct 24 '17 at 17:02
  • 2
    @JackFlamp The question does not explain *why* the OP is surprised by the behavior, nor does it show evidence of prior research. It may be a "fair" question, but it's not a "good" one. – azurefrog Oct 24 '17 at 17:02
  • sure, he could have elaborated but it is not obvious why splitting an empty string would result in an empty array even after reading the javadoc. – Jack Flamp Oct 24 '17 at 17:15
  • @JackFlamp Huh? Splitting an empty string doesn't result in an empty array. That's sort of the point. – azurefrog Oct 24 '17 at 17:17
  • @azurefrog oh shit I misread the code. I though it read `"".split(",").length == 0`. I get it then – Jack Flamp Oct 24 '17 at 17:19
  • @JackFlamp ...and that's why I think the question would be improved with some explanatory text ;-) – azurefrog Oct 24 '17 at 17:21
  • @azurefrog I stand corrected :) – Jack Flamp Oct 24 '17 at 17:22

2 Answers2

4

From javadoc:

If the expression does not match any part of the input then the resulting array has just one element, namely this string.

split(regex) -> split(regex, 0) so take a look on split(String regex, int limit)

pirho
  • 11,565
  • 12
  • 43
  • 70
3

This behavoiur is consistent:

"one".split(",") // {"one"}
"".split(",") // {""}

The empty String "" is a String like "one", so it behaves just like that (or any other String).

SilverNak
  • 3,283
  • 4
  • 28
  • 44