Splitting a space separated string

前端 未结 2 1234
说谎
说谎 2021-01-28 13:50
String numbers = \"5 1 5 1\";

So, is it:

String [] splitNumbers = numbers.split();

or:

String [] spli         


        
相关标签:
2条回答
  • 2021-01-28 14:23

    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"}

    0 讨论(0)
  • 2021-01-28 14:36

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

    0 讨论(0)
提交回复
热议问题