gpt4 book ai didi

Java 拆分在使用 | 时停在空白处作为分隔符

转载 作者:行者123 更新时间:2023-11-30 10:44:49 27 4
gpt4 key购买 nike

我正在使用 split() 拆分字符串,但我不知道为什么它在到达空格时停止。这是代码:

String a = "R|1|^^^fieldname1|18.8H |||||||||";

String[] b = a.split(Pattern.quote("|"));
also tried
String[] b = a.split("\\|");

System.out.println("Array length :"+b.length);

输出是:4

我找不到这背后的原因,请告诉我我错过了什么。

最佳答案

来自javadoc:

String.split(String pattern, int limit)

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.

可以看到split的代码:

public String[] split(String regex) {
return split(regex, 0);
}

lqst空值被去掉是正常的,限制为0。

如果传递 -1,这将采用每个空值。没有对空单元格进行右修剪。

String a = "R|1|^^^fieldname1|18.8H|||||||||";
String[] b = a.split("\\|", -1);
System.out.println(b.length);

输出为

 13

关于Java 拆分在使用 | 时停在空白处作为分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37317972/

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