4

As the title explains the query

Can somebody please explain the behavior of following two outputs.

"".split(",").length

gives output

1

where as

",".split(",").length

gives output

0
4
  • You should have looked up and read the javadoc before you asked this question. Commented Apr 25, 2013 at 13:52
  • How does this get 5 upvotes? No effort was done. Commented Apr 25, 2013 at 13:58
  • 3
    @SotiriosDelimanolis How did the answer get +15? ;-) Commented Apr 25, 2013 at 14:00
  • 1
    @DuncanJones SO is generous sometimes. Commented Apr 25, 2013 at 14:08

2 Answers 2

17

In the first case, the original string is returned, because the separator is not found.

From the API docs:

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

Sign up to request clarification or add additional context in comments.

6 Comments

Who would have guessed? The javadoc has the answer!
@StephenC To be slightly fair, the comment is only mentioned in the String.split(String regex, int limit) variant.
@DuncanJones - But I bet that the split(String regex) version says "see the other variant for details"!
Trailing empty strings are therefore not included in the resulting array. is part of the String#split(String) method. Not being fair. And Stephen is correct ^. This method works as if by invoking the two-argument split method...
@DuncanJones - True, though that is linked indirectly through the single-argument method's comment: "This method works as if by invoking the two-argument split method ."
|
0

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split(java.lang.String,%20int)

Trailing empty strings are discarded.

Try:

"Foo,".split(",").length // should be 1
",foo".split(",").length // should be 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.