Java字符串split()的异常行为 [英] Unexpected behavior of Java String split( )
问题描述
我正在尝试使用String split函数拆分字符串,这是一个示例:
String[] list = " Hello ".split("\\s+");
System.out.println("String length: " + list.length);
for (String s : list) {
System.out.println("----");
System.out.println(s);
}
这是输出:
String length: 2
----
----
Hello
如您所见,前导空格在String数组中变为空元素,但尾随空格不是.
有人知道为什么吗?
您需要使用 保留尾随空格-默认行为是根据答案以发表评论):>
要修剪前导空间,可以在分割String
String str = " Hello ".replaceAll("^\\s+", "");
String[] list = str.split("\\s+", -1);
I am trying to split a string using String split function, here's an example:
String[] list = " Hello ".split("\\s+");
System.out.println("String length: " + list.length);
for (String s : list) {
System.out.println("----");
System.out.println(s);
}
Here's the output:
String length: 2
----
----
Hello
As you can see, the leading whitespace becoming an empty element in the String array, but the trailing whitespace is not.
Does anyone know why?
You need to use the other split method which specifys the limit and specify a limit of -1
String[] list = " Hello ".split("\\s+", -1);
to preserve the trailing whitespace, - the default behavior is to omit the trailing spaces as per the javadoc
Edit (answer for comment):
To trim the leading space, you can strip off the leading space before splitting the String
String str = " Hello ".replaceAll("^\\s+", "");
String[] list = str.split("\\s+", -1);
这篇关于Java字符串split()的异常行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!