<分区>
假设您在 Java 中有这个表达式:
"adam".split("")
这是告诉 Java 使用空字符串 (""
) 作为分隔符来拆分 "adam"
。这产生:
["", "a", "d", "a", "m"]
为什么 Java 在开头包含一个空字符串,但在末尾不包含?使用这个逻辑,结果不应该是:
["", "a", "d", "a", "m", ""]
<分区>
假设您在 Java 中有这个表达式:
"adam".split("")
这是告诉 Java 使用空字符串 (""
) 作为分隔符来拆分 "adam"
。这产生:
["", "a", "d", "a", "m"]
为什么 Java 在开头包含一个空字符串,但在末尾不包含?使用这个逻辑,结果不应该是:
["", "a", "d", "a", "m", ""]
最佳答案
分隔符是正则表达式。正则表达式 ""
匹配字符串的最开头(在 adam
中的 a
之前)。 docs状态:
Splits this string around matches of the given regular expression.
因此该方法将围绕 a
之前的匹配进行拆分。文档还说:
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
和
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."
因此,尽管字符串末尾也有匹配项,但会丢弃尾随的空字符串。因此前导空字符串,但没有尾随空字符串。如果您想要尾随的空字符串,只需传递一个负值作为第二个参数:
"adam".split("", -1);
这行得通,因为引用自文档:
If n is non-positive then the pattern will be applied as many times as possible and the array can have any length.
要回答“为什么中间没有空字符串?”这个问题,正则表达式只会返回字符串中每个位置的单个匹配项。因此,字符串中的两个连续字符之间不能有两次匹配,所以回到我从文档中引用的第一句话,这些额外的空字符串将不会出现。
关于java - 使用空字符串作为分隔符拆分字符串会产生前导空字符串但不会产生尾随空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4549228/