java.lang.String.split(String regex) 关于字符分割方法的一点疑惑

图片描述

API如上,有点搞不懂第二个示例,boo:and:fooo分割的话
我预想的结果是:

{"b","",":and:f",""}

最后的空字符串是oo之间分割出来的,希望各位帮我解惑,谢谢。

阅读 5.7k
2 个回答

我想说,在JavaScript里,分出的是["b","",":and:f","",""],比较贴近我们的思维,但是Java里面split的一段源码这样写道:

// Construct result
int resultSize = matchList.size();
if (limit == 0)
    while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
        resultSize--;
String[] result = new String[resultSize];
return matchList.subList(0, resultSize).toArray(result);

可以看到while循环里面,如果结果集的最后元素是"",它会把它们一个一个地删除,这就是你所看到的结果的根本原因。
详细可以去看下我的博文:Java split源码分析

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

split 的第二个参数 limit

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

你要的结果可以传-1得到

foo.split("o",-1);

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题