String.split() 如果在字符串的最后部分,则忽略定界符之间的空值

String.split() ignoring empty values inbetween delimiters if on the final part of a string

给定以下字符串:

String s ="12/15|22:58:25|B|99.502||||A|100.501|||||";

我在打电话

int len = s.split("\|").length;

反正长度是 9,而不是应该的 13。

然而,如果我以这种方式修改所述字符串:

String s ="12/15|22:58:25|B|99.502||||A|100.501|||lol||";

长度是13! 怎么会?似乎 java 进行了某种优化,这不是必需的,因为字符串的那些部分可以在其他上下文中填充...

默认情况下 split 从结果数组中删除尾随的空字符串。要关闭此机制,请使用 split(regex, limit) 和负限制,如

split("\|", -1)

更多细节:
split(regex) 内部 returns split(regex, 0) 的结果,在这个方法的 documentation 中你可以找到(强调我的)

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.