gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 03:59:12 25 4
gpt4 key购买 nike

我正在尝试解析一些竖线分隔的记录。我有这段代码:

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]

访问 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));
}
}

最佳答案

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

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 参数 split

关于Java 的 String.split() 删除尾随的空条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11992932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com