Splitting a space separated string

大憨熊 提交于 2021-02-05 09:36:55

问题


String numbers = "5 1 5 1";

So, is it:

String [] splitNumbers = numbers.split();

or:

String [] splitNumbers = numbers.split("\s+");

Looking for: ["5","1","5","1"]

Any idea why neither of the .split lines will work? I tried reading answers about the regex, but I'm not getting anywhere.


回答1:


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 \.

When using \\s+ the String will be split on multiple whitespace characters (space, tab, etc).




回答2:


In your above case split("\s+");, you need to escape \ with another backslash, which is:

split("\\s+");

Or

split(" "); also can do it

Note that split("\\s+"); split any length of whitespace including newline(\n), tab(\t) while split(" "); will split only single space.

For example, when you have string separated with two spaces, say "5   1 5 1" ,

using split("\\s+"); you will get {"5","1","5","1"}

while using split(" "); you will get {"5","","1","5","1"}



来源:https://stackoverflow.com/questions/21034584/splitting-a-space-separated-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!