我正在尝试使用分隔符拆分值。但我发现了令人惊讶的结果
String data = "5|6|7||8|9||";
String[] split = data.split("\\|");
System.out.println(split.length);
我期望得到 8 个值。 [5,6,7,EMPTY,8,9,EMPTY,EMPTY]但我只得到 6 个值。
任何想法以及如何解决。无论 EMPTY 值来自任何地方,它都应该在数组中。
split(delimiter)
默认从结果数组中删除尾随的空字符串。要关闭此机制,我们需要使用 split(delimiter, limit)
的重载版本,并将 limit
设置为负值,例如
String[] split = data.split("\\|", -1);
更多细节:
split(regex)
内部返回 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.
异常(exception):
值得一提的是,删除尾随的空字符串才有意义只有当这样的空字符串是由拆分机制创建时。所以对于 "".split(anything)
因为我们不能将 ""
分割得更远,我们将得到结果 [""]
数组。
发生这种情况是因为此处没有发生拆分,因此 ""
尽管为空且尾随表示 original 字符串,而不是 created 的空字符串 split 过程。
我是一名优秀的程序员,十分优秀!