空字符串和单个分隔符字符串上的字符串拆分行为

时间:2011-11-16 18:54:38

标签: java scala

这是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"}

3 个答案:

答案 0 :(得分:7)

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

答案 1 :(得分:5)

根据java.util.regex.Pattern使用的String.split(..) source

"".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)

要包含尾随的空字符串,请使用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", ""}