3

我正在尝试解析一些管道分隔的记录。我有这个代码:

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, 1056209, , , KA3NDL, L]

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

有人知道为什么这是/一种解决方法吗?

编辑:

这有效:

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));
    }
}
4

4 回答 4

15

String.splitStrings没有限制参数从结果数组中删除所有尾随空。您需要包括一个限制:

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

来自String.split(String, int)

如果 n 为非正数,则该模式将尽可能多地应用,并且数组可以具有任意长度。如果 n 为零,则该模式将被应用尽可能多的次数,数组可以有任意长度,并且尾随的空字符串将被丢弃。

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

于 2012-08-16T18:09:56.493 回答
4

您可以将限制传递给split方法,以便保留尾随的空字符串:

"EN|1056209|||KA3NDL|L|||||||||||||||||||||".split("\\|", -1)
于 2012-08-16T18:10:55.967 回答
2

改用两个参数的版本split()。它允许您配置是否也应返回空字符串。

于 2012-08-16T18:10:13.147 回答
1

看看优秀的 Guava 库中的Splitter :

String input = "EN|1056209|||KA3NDL|L|||||||||||||||||||||";
Iterable<String> splitIter = Splitter.on("|").split(input);
System.out.println(splitIter);

输出:

[EN, 1056209, , , KA3NDL, L, , , , , , , , , , , , , , , , , , , , , ]
于 2012-08-16T18:12:08.363 回答