• 【转】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之前,都在末尾多加一个分割符
    如果是空串,会返回空的数组
    如果不是空串,也不会影响原来的分割结果
  • 相关阅读:
    小写数字转化为大写工具类
    java中关于日期类Calendar的简单使用
    ArrayList用法总结
    滚动条(附:定时调用)
    百度Echarts的使用总结
    Datatables 使用总结
    字符串(String、StringBuffer、StringBuilder)
    sqlserver 脚本方式导出数据到excel
    前端面试
    数据库面试
  • 原文地址:https://www.cnblogs.com/amibandoufu/p/10821641.html
Copyright © 2020-2023  润新知