gpt4 book ai didi

java - 不确定在这种情况下字符串拆分实际上是如何工作的

转载 作者:太空狗 更新时间:2023-10-29 22:45:58 24 4
gpt4 key购买 nike

我没有得到以下内容:

在以下字符串中:

String s = "1234;x;;y;";

如果我这样做:
String[] s2 = s.split(";");

我得到 s2.length 为 4 和

s2[0] = "1234";  
s2[1] = "x";
s2[2] = "";
s2[3] = "y";

但在字符串中:String s = "1234;x;y;;";

我得到:

s2.length 为 3 和

s2[0] = "1234";  
s2[1] = "x";
s2[2] = "y";

?

有什么区别,在后一种情况下我也没有得到 4?

更新:
使用 -1 并不是我所期望的行为。
我的意思是最后一个分号是 String 的结尾,所以在后一个示例中我还期望 4 作为数组的长度

最佳答案

来自docs ,

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.

更新:

您有五个由 分隔的子字符串; 在第二种情况下,它们是 1234xy。根据文档,拆分操作产生的所有空子字符串(末尾)都将被消除。详情看here .

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.

例如,字符串 boo:and:foo 使用这些参数产生以下结果:

Regex   Limit   Result
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" } // all the empty substrings at the end were eliminated

关于java - 不确定在这种情况下字符串拆分实际上是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9290518/

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