`
qindongliang1922
  • 浏览: 2145139 次
  • 性别: Icon_minigender_1
  • 来自: 北京
博客专栏
7265517b-f87e-3137-b62c-5c6e30e26109
证道Lucene4
浏览量:116259
097be4a0-491e-39c0-89ff-3456fadf8262
证道Hadoop
浏览量:124512
41c37529-f6d8-32e4-8563-3b42b2712a50
证道shell编程
浏览量:58370
43832365-bc15-3f5d-b3cd-c9161722a70c
ELK修真
浏览量:70306
社区版块
存档分类
最新评论

你不知道的Java的split的小问题

    博客分类:
  • JAVA
阅读更多

有时候,我们的一些业务数据,有些定义的是按某个分割符分割数据,然后一行一行的,处理这种数据时候,要务必小心,因为它简单,不用维护类似json格式的数据或者一个对象,而是直接通过下标位置来访问数据的,相信这种场景大家也都接触过,当然弊端也是显而易见的,如果位置放错或者代码使用不当,都会造成一些问题,所以使用这种方式时,一会都会约定一些内容,比如行分隔符,列分割符等,下面来看一个小问题,先看下面一段代码:


      String line1="1#2#3";//期待长度3,结果是3
        System.out.println(line1.split("#").length);

        String line2="1#2#3##";//期待长度5,实际结果是3 , 有问题? 
        System.out.println(line2.split("#").length);



运行完,你会发现第二段代码的数组的长度竟然与你想的不一致?为什么?我们来看
官网api解释:

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

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

 



如果limit是负数,那么它会尽可能匹配到所有的这个数组的个数,如果是0那么尽可能匹配出现的元素,但是空字符串将会被就丢弃,但我们不希望它丢弃,因为丢弃就意味着有业务字段缺失,所以来看下最终的写法:

        String line3="1#2#3##";//正确的写法 
        System.out.println(line3.split("#",-1).length);

6
3
分享到:
评论
4 楼 flicking2015 2016-01-25  
细节问题。
3 楼 williamou 2016-01-22  
用apache StringUtils的split相关方法吧
2 楼 qindongliang1922 2016-01-22  
yuxuguang 写道
可以试试guava的Splitter

Splitter底层也是调的jdk源码吧
1 楼 yuxuguang 2016-01-22  
可以试试guava的Splitter

相关推荐

Global site tag (gtag.js) - Google Analytics