前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >你不知道的Java的split的小问题

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

作者头像
我是攻城师
发布2018-05-14 15:27:58
4900
发布2018-05-14 15:27:58
举报
文章被收录于专栏:我是攻城师

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

Java代码

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

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

Java代码

  1. /**
  2. 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.
  3. */
  4. public String[] split(String regex,int limit)

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

Java代码

  1. String line3="1#2#3##";//正确的写法
  2. System.out.println(line3.split("#",-1).length);
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2016-01-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 我是攻城师 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档