3

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

2 回答 2

17

在第一种情况下,返回原始字符串,因为没有找到分隔符。

API 文档

如果表达式与输入的任何部分都不匹配,则结果数组只有一个元素,即这个字符串。

于 2013-04-25T13:50:25.313 回答
0

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

尾随的空字符串被丢弃。

尝试:

"Foo,".split(",").length // should be 1
",foo".split(",").length // should be 1
于 2013-04-25T13:56:40.063 回答