问题描述
我需要 split()
方法的帮助。
我有以下字符串
:
I need help with the split()
method. I have the followingString
:
String values = "0|0|0|1|||0|1|0|||";
我需要将值放入数组中。有3种可能的字符串:0,1和
I need to put the values into an array. There are 3 possible strings: "0", "1", and ""
我的问题是,当我尝试使用 split()
:
My problem is, when i try to use split()
:
String[] array = values.split("\\|");
我的值仅保存到最后0.看起来像|||部分被修剪。
我做错了什么?
My values are saved only until the last 0. Seems like the part "|||" gets trimmed.What am i doing wrong?
谢谢
推荐答案
(强调我的):
This behavior is explicitly documented in String.split(String regex)
(emphasis mine):
如果你想要包含那些尾随的空字符串,你需要使用,第二个参数为负值( limit
):
If you want those trailing empty strings included, you need to use String.split(String regex, int limit)
with a negative value for the second parameter (limit
):
String[] array = values.split("\\|", -1);
这篇关于Java将字符串拆分为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!