简体   繁体   English

字符串拆分方法行为

[英]String split method behavior

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 返回长度为1的String数组

String[] split = "Java".split(",");
System.out.println(split.length);
Returns array of String with length 1 返回长度为1的String数组

How to differentiate?? 如何区分?

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开发人员不会添加其他情况。

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();

它返回原始字符串(在这种情况下是空字符串),因为没有,要分开。

它返回一个因为你正在测量split数组的大小,它包含一个元素:一个空字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM