String.split()如果在字符串的最后部分,则忽略定界符之间的空值 [英] String.split() ignoring empty values inbetween delimiters if on the final part of a string

查看:50
本文介绍了String.split()如果在字符串的最后部分,则忽略定界符之间的空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下字符串:

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

我在打电话

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

无论如何长度都是9,而不是应该的13.

Anyway length is 9, not 13 as it should be.

尽管如此,如果我以这种方式修改了所说的字符串:

Nevertheless, if I modify said string in this way:

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

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

Length is 13! How come?It just seems that java makes some kind of optimization, which is not required as those parts of string could be populated in some other context...

推荐答案

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

By default split removes trailing empty strings from result array. To turn off this mechanism use split(regex, limit) with negative limit like

split("\\|", -1)

更多细节:
split(regex)在内部返回 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.

这篇关于String.split()如果在字符串的最后部分,则忽略定界符之间的空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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