2011-11-16 59 views
8

这是this question的后续行为。空字符串和单分隔符字符串上的字符串拆分行为

问题在下面的第二行。

"".split("x"); //returns {""} // ok 
"x".split("x"); //returns {} but shouldn't it return {""} because it's the string before "x" ? 
"xa".split("x"); //returns {"", "a"} // see?, here "" is the first string returned 
"ax".split("x"); //returns {"a"} 
+1

参见[SI-5096(https://issues.scala-lang.org/browse/SI-5069) “的Bug分裂()时,分隔符出现在字符串的结束” – 4e6

+1

这就是为什么谷歌Guava创建了com.google.common.base.Splitter – Schildmeijer

回答

5

作为每java.util.regex.Pattern​​,其String.split(..)用途,

"".split("x"); // returns {""} - valid - when no match is found, return the original string 
"x".split("x"); // returns {} - valid - trailing empty strings are removed from the resultant array {"", ""} 
"xa".split("x"); // returns {"", "a"} - valid - only trailing empty strings are removed 
"ax".split("x"); // returns {"a"} - valid - trailing empty strings are removed from the resultant array {"a", ""} 
+2

所以它的行为正确,因为它调用的方法...的行为方式?我想知道当我用这样的理由结束下一个错误报告时,我的老板会说什么。 –

+0

@Kim Stebel,SO'既不是臭虫追踪者,也不是我为它修复错误。这篇文章基本上要求澄清,而不是一个解决方案,我只是试图说明为什么split方法表现得那么好。别紧张。 – srkavin

7

不,因为根据the relevant javadoc“尾随空串将被丢弃”。

+0

那么为什么不在第一行中丢弃呢? (分割空字符串) – snappy

+0

这应该被理解为“结果数组末尾的空字符串将被丢弃”。 – madth3

+0

我想它看到空字符串作为第一个标记,然后在它之后拆分,所以技术上它是一个前导空字符串 –

0

为了包括在后空字符串,则使用其他实施split

"".split("x", -1); // returns {""} - valid - when no match is found, return the original string 
"x".split("x", -1); // returns {"", ""} - valid - trailing empty strings are included in the resultant array {"", ""} 
"xa".split("x", -1); // returns {"", "a"} - valid 
"ax".split("x", -1); // returns {"a", ""} - valid - trailing empty strings are included in the resultant array {"a", ""}