Behaviour of String.split() when input is empty

2020-02-06 10:42发布

问题:

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

回答1:

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.



回答2:

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