我不明白这段代码的输出:
public class StringDemo{
public static void main(String args[]) {
String blank = "";
String comma = ",";
System.out.println("Output1: "+blank.split(",").length);
System.out.println("Output2: "+comma.split(",").length);
}
}
得到以下输出:
Output1: 1
Output2: 0
最佳答案
文档:
对于:System.out.println("Output1: "+blank.split(",").length);
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. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
它只会返回整个字符串,这就是它返回 1 的原因。
对于第二种情况,String.split
会丢弃,
所以结果为空。
String.split silently discards trailing separators
关于java - 来自 String.split 的令人困惑的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25056607/