Java之split result array 长度问题

      今天遇到一个BUG,给定数据"a,b,c,d,e“,用"a,b,c,d,e“.split(",")函数生成的数组长度是5。但是,如果给定的数组是“a,b,c,d,”,这种格式,情况就不一样了,我之前一直认为"a,b,c,d,“.split(",")的数组长度是5,但是事实上,长度是4

 

参考代码片段:

 

String a = "a,b,c,d,";
String b = "a,b,c,d,e";
System.out.println(a.split(",").length);
System.out.println(b.split(",").length);

 

于是查看String.split的源代码:

public String[] split(String regex) {
    return split(regex, 0);
}

 

找到方法说明里面有这么一段:

写道
Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

  

标记红色的这句话告诉我,在末尾的空字符串不会被包含在结果数组。现在应该很清楚了,可能是我愚笨了,理解错误了,在此标记一下。

 

那么如果遇到“a,b,c,d,”这种数据,想要让返回的数组包含最后的空字符串,即数组长度是5,有没有办法呢?

接着查看JDK的源码,找到split的重载方法:

 

 public String[] split(String regex, int limit) {
	return Pattern.compile(regex).split(this, limit);
    }

 

这个方法说明中有一段话:

 写道

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

 这段话告诉我有两种方式可以实现我的需求:

“a,b,c,d,”.split(",",-1);

“a,b,c,d,”.split(",",5);

 limit要么是负数,要么大于等于result array的长度。

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值