gpt4 book ai didi

java - 为什么 String.split 以不同方式处理字符串的开始和结束部分?

转载 作者:行者123 更新时间:2023-12-03 23:14:29 24 4
gpt4 key购买 nike

例子:

String s = ":a:b:c:";
s.split(":");
// Output: [, a, b, c]

来自 Java 文档:

此方法返回的数组包含此字符串的每个子字符串,这些子字符串由与给定表达式匹配的另一个子字符串终止或由字符串末尾终止。

为什么不考虑结束空字符串而考虑开始空字符串?起始空字符串以“:”结束,结束空字符串以字符串末尾结束。所以两者都应该列出,不是吗?

最佳答案

当您不提供 limit 时,split方法不返回尾随的空匹配。引用 Javadocs:

Splits this string around matches of the given regular expression. 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 的 2 参数版本,然后传入一个负数限制,返回数组的大小将不受限制;你会得到尾随的空字符串。

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.

我认为 Javadocs 在说 n 时指的是 limit

关于java - 为什么 String.split 以不同方式处理字符串的开始和结束部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16403545/

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