Java中String的split()方法的一些疑问和试验

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

 split函数是用于使用特定的切割符(regex)来分隔字符串成一个字符串数组,这里我就不讨论第二个参数(可选)的含义详见官方API说明

 

我在做项目期间曾经遇到一个“bug”,就是当split函数处理空字符串时,返回数组的数组竟然有值。。。查完API才发现就是这么规定的。

官方API 写道
If the expression does not match any part of the input then the resulting array has just one element, namely this string.

 原来我不能小看空字符串,它也是字符串的一种,当split函数没有发现匹配的分隔符时,返回数组就只包含一个元素(该字符串本身)。以为这样就结束了,幸亏我做了几个试验,忽然又发现了一些问题,代码如下:

public class Split {

	public static void main(String[] args) {
		String str1 = "a-b";		
		String str2 = "a-b-";
		String str3 = "-a-b";
		String str4 = "-a-b-";
		String str5 = "a";
		String str6 = "-";
		String str7 = "--";
		String str8 = "";	//等同于new String()
		
		getSplitLen(str1);
		getSplitLen(str2);
		getSplitLen(str3);
		getSplitLen(str4);
		getSplitLen(str5);
		getSplitLen(str6);
		getSplitLen(str7);
		getSplitLen(str8);
	}
	
	public static void getSplitLen(String demo){
		String[] array = demo.split("-");
		int len = array.length;
		System.out.print("\"" + demo + "\"长度为:" + len);
		if(len >= 0){
			for(int i=0; i<len; i++){
				System.out.print(" \""+array[i]+"\"");
			}			
		}
		System.out.println();
	}

}

 运行结果:

"a-b"长度为:2 "a" "b"
"a-b-"长度为:2 "a" "b"
"-a-b"长度为:3 "" "a" "b"
"-a-b-"长度为:3 "" "a" "b"
"a"长度为:1 "a"
"-"长度为:0
"--"长度为:0
""长度为:1 ""

 

和我想的还是不大一样,因为不知道源码也不知道具体是怎么实现的,我的理解如下:

  1. 当字符串只包含分隔符,返回数组没有元素;
  2. 当字符串不包含分隔符时,返回数组只包含一个元素(该字符串本身);
  3. 字符串最尾部出现的分隔符可以看成不存在,不影响字符串的分隔;
  4. 字符串最前端出现的分隔符将分隔出一个空字符串以及剩下的部分的正常分隔;

 

javascript也有split()函数,我想应该也是类似的,还没有来得及尝试。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值