Java String拆分删除了空值 [英] Java String split removed empty values

查看:150
本文介绍了Java String拆分删除了空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用分隔符拆分Value。
但我发现了令人惊讶的结果

I am trying to split the Value using a separator. But I am finding the surprising results

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个值。

I am expecting to get 8 values. [5,6,7,EMPTY,8,9,EMPTY,EMPTY] But I am getting only 6 values.

任何想法和如何解决。无论EMPTY值是否在任何地方,它都应该在数组中。

Any idea and how to fix. No matter EMPTY value comes at anyplace, it should be in array.

推荐答案

split(delimiter)默认情况下从结果数组中删除尾随的空字符串。要关闭此机制,我们需要使用 split(分隔符,限制)的重载版本,并将 limit 设置为负值喜欢

split(delimiter) by default removes trailing empty strings from result array. To turn this mechanism off we need to use overloaded version of split(delimiter, limit) with limit set to negative value like

String[] split = data.split("\\|", -1);

更多细节:

拆分(正则表达式) 在内部返回 split(regex,0)的结果,并在文档(强调我的)

Little more details:
split(regex) internally returns result of split(regex, 0) and in documentation of this method you can find (emphasis mine)


limit 参数控制模式的应用次数,因此会影响结果数组的长度。

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.

如果限额 n 大于零,则该模式将应用于大多数n - 1次,数组的长度不会大于n,并且数组的最后一个条目将包含除最后一个匹配分隔符之外的所有输入。

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.

如果 n 非正面,那么该模式将被应用多次尽可能的数组可以有任何长度。

If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.

如果 n ,那么该模式将尽可能多地应用,数组可以有任何长度,尾随空字符串将被丢弃

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.

异常

值得一提的是,只有当这种空字符串由分裂机制创建时,删除尾随空字符串才有意义。所以对于。split(nothing)因为我们无法拆分我们将得到更多结果 [] 数组。

这是因为拆分没有发生在这里,所以尽管是空的并且尾随代表原始字符串,而不是通过拆分过程创建的空字符串。

It is worth mentioning that removing trailing empty string makes sense only if such empty strings ware created by split mechanism. So for "".split(anything) since we can't split "" farther we will get as result [""] array.
It happens because split didn't happen here, so "" despite being empty and trailing represents original string, not empty string which was created by splitting process.

这篇关于Java String拆分删除了空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆