加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java的String.split()删除尾随空条目

发布时间:2020-12-15 02:02:04 所属栏目:Java 来源:网络整理
导读:我正在尝试解析一些管道分隔的记录.我有这个代码: public class Test { public static void main(String[] args) throws Exception { String[] components = "EN|1056209|||KA3NDL|L|||||||||||||||||||||".split("|"); System.out.println(java.util.Arr
我正在尝试解析一些管道分隔的记录.我有这个代码:

public class Test {
    public static void main(String[] args) throws Exception {
        String[] components = "EN|1056209|||KA3NDL|L|||||||||||||||||||||".split("|");
        System.out.println(java.util.Arrays.toString(components));
    }
}

你希望它打印:

[EN,1056209,KA3NDL,L,]

但事实并非如此.它打印:

[EN,L]

访问components数组的length属性表明它正在正确打印.

任何人都知道为什么这是一个解决方法?

编辑:

这有效:

public class Test {
    public static void main(String[] args) throws Exception {
        String[] components = "EN|1056209|||KA3NDL|L|||||||||||||||||||||".split("|",-1);
        System.out.println(java.util.Arrays.toString(components));
    }
}

解决方法

没有limit参数的 String.split会从结果数组中删除所有尾随的空字符串.您需要包含一个限制:

String str = "EN|1056209|||KA3NDL|L|||||||||||||||||||||";
String[] components = str.split("|",-1);

String.split(String,int)开始:

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.

调用String.split(String)等效于调用限制为0的2参数拆分.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读