java split(String regex, int limit) 和 split(String regex)的区别

631 阅读1分钟

String[] split(String regex, int limit)

public String[] split(String regex, int limit)

其中regex为分割正则表达式,limit为分割次数限制;

limit=1时:表示把字符串分割成1份

String[] strLst = "1,2,3,4,".split(",", 1);  --> [1,2,3,4,]

limit=2时:表示把字符串分割成2份

String[] strLst = "1,2,3,4,".split(",", 2);  --> [1, 2,3,4,]

limit=5时:表示把字符串分割成5份

String[] strLst = "1,2,3,4,".split(",", 5);  --> [1, 2, 3, 4, ]

limit=6时:表示把字符串分割成6份、但是最多只能分5分、会自动分5分

String[] strLst = "1,2,3,4,".split(",", 6);  --> [1, 2, 3, 4, ]

limit=0时:字符串被尽可能多的分割,但是尾部的空字符串会被抛弃

String[] strLst = "1,2,3,4,".split(",", 0);  --> [1, 2, 3, 4]

limit < 0时:字符串被尽可能多的分割,而且尾部的空字符串不会被抛弃

String[] strLst = "1,2,3,4,".split(",", -1); --> [1, 2, 3, 4, ]
String[] strLst = "1,2,3,4,".split(",", -2); --> [1, 2, 3, 4, ]

String[] split(String regex)

String[] split(String regex)

对于没有 limit 参数的 split函数,等价于 limt = 0 的情况,尾部的空字符串被舍弃掉:

String[] strLst = "1,2,3,4,".split(","); --> [1, 2, 3, 4]

参考

www.cnblogs.com/yxmfighting…