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

标签 java regex string class core

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

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/

相关文章:

java - 从 Android 的下载文件夹中获取 pdf 或 doc 文件

java - Japplet 表单从数据库检索值

java - 如何指定给定数字是否具有整数平方根?

匹配文件名的正则表达式

string - 用于在目录和所有子目录中查找字符串的批处理脚本

r - 如何在R中的Unicode字符串中找到 "real"个字符数

java - java 和 Scala 中非 Ascii 字符的子字符串

java - 如何在webview中实现后退按钮?

.net - 匹配 YYYYMM 值的正则表达式

regex - 合并两个 sed 命令