我没有以下内容:

在以下String中:
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



更新:

您有五个由;分隔的子字符串。在第二种情况下,它们是1234xy。根据文档,将消除所有由拆分操作导致的空子字符串(最后)。
有关详细信息,请查看here



例如,字符串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

10-05 21:12
查看更多