示例:
String s = ":a:b:c:";
s.split(":");
// Output: [, a, b, c]
来自Java Doc:
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string.
为什么起始空字符串被认为是结束空字符串不在哪里? 起始空字符串以“:”结尾,结束空字符串以字符串结尾终止。所以两者都应该列出,如果不是的话?
答案 0 :(得分:6)
当您不提供limit
时,split
方法不会返回尾随空匹配。引用Javadocs:
围绕给定正则表达式的匹配拆分此字符串。 此方法的工作方式就像通过调用双参数split方法一样 给定的表达式和一个零的限制参数。尾随空 因此,字符串不包含在结果数组中。
如果使用split
的2参数版本,则传入负限制,并且不会限制返回数组的大小;你会得到空字符串。
如果n是非正数,那么模式将被应用多次 可能,阵列可以有任何长度。
我认为Javadocs在提及limit
时指的是n
。
答案 1 :(得分:2)
它的行为与定义in the javadoc相同。要获得尾随空字符串,您可以使用the other split method, that takes two arguments:
s.split(":", -1);
// Output: [, a, b, c, ]
答案 2 :(得分:2)
如javadocs中所述:
Trailing empty strings are therefore not included in the resulting array.
.split还支持第二个参数(limit),它会更改默认行为,如下所示:
String s = ":a:b:c:";
s.split(":", 0); //"Default" Split behaviour --> [, a, b, c]
s.split(":", 1); //Array length == 1 --> [:a:b:c:]
s.split(":", 2); //Array length == 2 --> [, a:b:c:]
s.split(":", 3); //Array length == 3 --> [, a, b:c:]
s.split(":", -1); //Any length. Trailling empty spaces are not ommited --> [, a, b, c, ]
正如旁注,Google Guava提供了许多用于加速Java开发的类,例如Splitter,它可以满足您的需求:
private static final Splitter SPLITTER = Splitter.on(':')
.trimResults()
.omitEmptyStrings();
//returns ["a", "b", "c"]
SPLITTER.split(":a:b::::c:::")
答案 3 :(得分:0)
在此方法中,尾随空字符串将被丢弃。 您可以从here
获取详细信息