我刚刚做了一些变通,并对结果感到惊讶。让我解释一下。
String str = "aaa.jpg";
String[] str1 = str.split("."); //output of this is empty array with size 0
str.contains("."); //output of this is true.
谁能解释一下,为什么 split()
方法无法识别 "."
,而 contains()
可以识别 "."
.
最佳答案
split()
使用正则表达式,和 .
in regex表示任何字符(换行符除外)。此外,结果数组为空的原因是因为 split()
丢弃尾随的空字符串(但是,您可以通过提供负的第二个参数来让它保留空字符串):
This method works as if by invoking the two-argument
split
method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
可以转义 .
以匹配文字句点:
str.split("\\.")
相比之下,contains()
适用于文字字符串,因此 .
只是 .
.
关于java - 在内部解释 split 和 contains 方法如何适用于 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18539727/