在这种情况下,不确定字符串拆分如何实际工作

Jim*_*Jim 16 java regex string split

我没有得到以下内容:

在以下内容中String:

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

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

s2.length变成了4岁

s2[0] = "1234";  
s2[1] = "x";  
s2[2] = "";  
s2[3] = "y"; 
Run Code Online (Sandbox Code Playgroud)

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

我明白了:

s2.length 成为3和

s2[0] = "1234";  
s2[1] = "x";  
s2[2] = "y"; 
Run Code Online (Sandbox Code Playgroud)

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

更新:
使用-1不是我期待的行为.
我的意思是最后一个分号是结尾的String所以在后一个例子中我也期待4作为数组的长度

Pul*_*yal 10

文档中,

此方法的工作方式就像调用带有给定表达式和limit参数为零的双参数split方法一样.因此,结尾的空字符串不包含在结果数组中.

更新:

你有五子分隔;在第二种情况下,这些都是1234,x,y, and .根据文档,将消除由拆分操作产生的所有空子串(在末尾).有关详情,请查看此处.

如果n为零,那么模式将被应用尽可能多的次数,数组可以具有任何长度,并且将丢弃尾随的空字符串.

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
Run Code Online (Sandbox Code Playgroud)