gpt4 book ai didi

java - 来自 String.split 的令人困惑的输出

转载 作者:IT老高 更新时间:2023-10-28 20:29:51 24 4
gpt4 key购买 nike

我不明白这段代码的输出:

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

guava StringsExplained

关于java - 来自 String.split 的令人困惑的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25056607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com