java 拆分时如何让Java忽略字符串中的空格数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4861803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:22:31  来源:igfitidea点击:

How do I make Java ignore the number of spaces in a string when splitting?

java

提问by tshepang

Possible Duplicate:
How do I split a string with any whitespace chars as delimiters?

可能的重复:
如何拆分带有任何空格字符作为分隔符的字符串?

Both of these Python lines gives me exactly the same list:

这两个 Python 行都给了我完全相同的列表:

print("1 2 3".split())
print("1  2   3".split())

Output:

输出:

['1', '2', '3']
['1', '2', '3']

I was surprised when the Java 'equivalents' refused:

当 Java 'equivalents' 拒绝时,我感到很惊讶:

System.out.println(Arrays.asList("1 2 3".split(" ")));
System.out.println(Arrays.asList("1  2   3".split(" ")));

Output:

输出:

[1, 2, 3]
[1, , 2, , , 3]

How do I make Java ignore the number of spaces?

如何让 Java 忽略空格数?

回答by Arnaud Le Blanc

Try this:

试试这个:

"1  2  3".split(" +")

// original code, modified:
System.out.println(Arrays.asList("1 2 3".split(" +")));
System.out.println(Arrays.asList("1  2   3".split(" +")));

The argument passed to split()is a Regex, so you can specify that you allow the separator to be one or more spaces.

传递给的参数split()是一个正则表达式,因此您可以指定允许分隔符为一个或多个空格。

I you also allow tabs and other white-space characters as separator, use "\s":

如果您还允许制表符和其他空白字符作为分隔符,请使用“\s”:

"1  2  3".split("\s+")

And if you expect to have trailing or heading whitespaces like in " 1 2 3 ", use this:

如果您希望有像 in 那样的尾随或标题空格" 1 2 3 ",请使用以下命令:

 "  1 2   3   ".replaceAll("(^\s+|\s+$)", "").split("\s+")

回答by Uszui

How about using a neat regular expression? Note that according to Java API documentation, String.splitwill take a regular expression string parameter.

使用简洁的正则表达式怎么样?请注意,根据 Java API 文档,String.split将采用正则表达式字符串参数。

"1 2   3".split("\s+")

回答by Costi Ciudatu

I think this should do:

我认为应该这样做:

yourString.trim().split("\s+");

回答by AlexR

I prefer "1 2 3".split("\s+")than "1 2 3".split(" +"). When you use \sinstead of " " it is more readable and safer.

我喜欢"1 2 3".split("\s+")"1 2 3".split(" +")。当您使用\s而不是“”时,它更具可读性和安全性。