split函数 - java.lang.String.split(String regex) 关于字符分割方法的一点疑惑
天蓬老师
天蓬老师 2017-04-17 12:00:47
[Java讨论组]

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

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

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

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

全部回复(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);

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号