java 字符串拆分方法行为
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12148991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
String split method behavior
提问by Srujan Kumar Gulla
I don't see why does the following output makes sense.
我不明白为什么以下输出有意义。
String split method on an empty String returning an array of String with length 1
空字符串上的字符串拆分方法返回长度为 1 的字符串数组
String[] split = "".split(",");
System.out.println(split.length);
Returns array of String with length 1
String[] split = "".split(",");
System.out.println(split.length);
返回长度为 1 的字符串数组
String[] split = "Java".split(",");
System.out.println(split.length);
Returns array of String with length 1
String[] split = "Java".split(",");
System.out.println(split.length);
返回长度为 1 的字符串数组
How to differentiate??
怎么区分??
回答by Simeon Visser
From the documentation:
从文档:
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.
此方法返回的数组包含此字符串的每个子字符串,这些子字符串由与给定表达式匹配的另一个子字符串终止,或由字符串的末尾终止。
To answer your question, it does what it is expected to do: the returned substring is terminated by the end of the input string (as there was no ,
to be found). The documentation also states:
要回答您的问题,它会执行预期的操作:返回的子字符串在输入字符串的末尾终止(因为,
找不到)。该文件还指出:
If the expression does not match any part of the input then the resulting array has just one element, namely this string.
如果表达式不匹配输入的任何部分,则结果数组只有一个元素,即这个字符串。
Note that this is a consequence of the first statement. It is not an additional circumstance that the Java developers added in case the search string could not be found.
请注意,这是第一个语句的结果。这不是 Java 开发人员在找不到搜索字符串的情况下添加的附加情况。
回答by Chris Gerken
I hit this, too. What it's returning is the string up to but not including the split character. If you want to get no strings, use StringTokenizer:
我也打过这个 它返回的是字符串,但不包括拆分字符。如果你不想得到任何字符串,请使用 StringTokenizer:
StringTokenizer st = new StringTokenizer(someString,',');
int numberOfSubstrings = st.countTokens();
回答by Jeff Storey
It's returning the original string (which in this case is the empty string) since there was no , to split on.
它返回原始字符串(在这种情况下是空字符串),因为没有 , 可以拆分。
回答by Bobulous
It returns one because you are measuring the size of the split array, which contains one element: an empty string.
它返回 1,因为您正在测量拆分数组的大小,其中包含一个元素:一个空字符串。