拆分以空格分隔的字符串 [英] Splitting a space separated string
本文介绍了拆分以空格分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
String numbers = "5 1 5 1";
是吗:
String [] splitNumbers = numbers.split();
或:
String [] splitNumbers = numbers.split("\s+");
寻找:["5","1","5","1"]
知道为什么 .split
行都不起作用吗?我尝试阅读有关正则表达式的答案,但一无所获.
Any idea why neither of the .split
lines will work? I tried reading answers about the regex, but I'm not getting anywhere.
推荐答案
您必须使用额外的 \
对正则表达式进行转义,因为 \
表示转义字符:
You must escape the regex with an additional \
since \
denotes the escape character:
public static void main(String[] args) {
String numbers = "5 1 5 1";
String[] tokens = numbers.split("\\s+");
for(String token:tokens){
System.out.println(token);
}
}
因此附加的 \
转义了下一个 \
,然后将其视为文字 \
.
So the additional \
escapes the next \
which is then treated as the literal \
.
当使用 \\s+
时,字符串将被分割成多个空白字符(空格、制表符等).
When using \\s+
the String will be split on multiple whitespace characters (space, tab, etc).
这篇关于拆分以空格分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文