java split limit_java split(String regex, int limit) 的使用

项目中遇到了这样一个问题,对 String str = ",," 调用 split(",")方法,预期结果是返回一个长度为 3 的String数组,且每一个元素都为空字符串 ""。但实际结果返还的是一个空数组,长度为 0 。

百度之,原来java中还有 split(String regex, int limit)这中用法,String[] java.lang.String.split(String regex, int limit),其中regex为分割正则表达式,limit为分割次数限制,官方文档这样解释:

1. The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

当 limit  > 0的时候,str将被分割 limit - 1次:

1 String str = ",,,,";2 String [] strLst = str.split(",", 2);3 System.out.println(strLst.length);4

5 for(String e : strLst) {6 System.out.println(e);7 }

输出为:

2,,,

2. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.

当 limit < 0 的时候,str将被尽可能多的分割:

1

2 String str = ",,,,";3 String [] strLst = str.split(",", -1);4 System.out.println(strLst.length);5

6 for(String e : strLst) {7 System.out.println(e);8 }

输出为:

5

3.  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

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

1 String str = ",,,,";2 String [] strLst = str.split(",", 0);3 System.out.println(strLst.length);4 for(String e : strLst) {5 System.out.println(e);6 }7

8 str = "a,b,,,";9 strLst = str.split(",", 0);10 System.out.println(strLst.length);11 for(String e : strLst) {12 System.out.println(e);13 }

输出为:

0

2a

b

对于 没有 limit 参数的 split函数, 官方解释如下:

This method works as if by invoking the two-argument

也就是等价于 limt = 0 的情况,尾部的空字符串被舍弃掉:

1 String str = "a,b,,,";2 String [] strLst = str.split(",");3 System.out.println(strLst.length);4 for(String e : strLst) {5 System.out.println(e);6 }

输出为:

2a

b

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值