gpt4 book ai didi

java - 为什么 "||".split ("\\|").length 返回 0 而不是 3?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:08:54 25 4
gpt4 key购买 nike

当拆分表达式中有相邻的分隔符时,我希望为 null 或空字符串——不会将其删除。

Java代码如下:

public class splitter {
public static void main(String args[]) {
int size = "||".split("\\|").length;
assert size == 3 : "size should be 3 and not " + size;
}
}

我希望得到 { "", "", ""} 或 { null, null, null }。两者都可以。

也许有一种正则表达式不会被空字所迷惑?

最佳答案

根据javadoc :

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

split(String, int) 的 javadoc阐述:

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("\\|", -1)

关于java - 为什么 "||".split ("\\|").length 返回 0 而不是 3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11514769/

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