【转】java的string中,关于split空串总会返回单个元素的数组

原地址:http://blog.sina.com.cn/s/blog_6f3da9650102x03c.html

 

public class Split {  
  
    public static void main(String[] args) {  
        String str1 = "a-b";          
        String str2 = "a-b-"; 
    String str22 = "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(Str22); 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 System.out.print(" \""+array[i]+"\""); } } System.out.println(); } }
运行结果:
"a-b"长度为:2 "a" "b"
"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 ""

 

  • 当字符串只包含分隔符时,返回数组没有元素;
  • 当字符串不包含分隔符时,返回数组只包含一个元素(该字符串本身);
  • 字符串最尾部出现的分隔符可以看成不存在,不影响字符串的分隔;
  • 字符串最前端出现的分隔符将分隔出一个空字符串以及剩下的部分的正常分隔;
 
我的做法, 调用split之前,都在末尾多加一个分割符
如果是空串,会返回空的数组
如果不是空串,也不会影响原来的分割结果

转载于:https://www.cnblogs.com/amibandoufu/p/10821641.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值