Java: Splitting a string by whitespace when there is a variable number of whitespaces between words?

前端 未结 8 1136
醉话见心
醉话见心 2021-01-01 03:17

I have the following:

String string = \"1-50  of 500+\";
String[] stringArray = string.split(\" \");

Printing out all the elements in this

相关标签:
8条回答
  • 2021-01-01 03:42

    Your Program is correct but you put two space after 1-50. So Its giving you that output. Remove one space and you are done. No need to change the code. But if there is a two space then you should use string.split("\\s+")

    0 讨论(0)
  • 2021-01-01 03:49

    To fix the space problem, after splitting, you can use .trim() to remove the white space.

    Something like this should work.

    for(int x=0; x<stringArray.length(); x++){
        stringArray[x] = stringArray[x].trim();
    }
    
    0 讨论(0)
  • 2021-01-01 03:51

    Use \\s+ to split on spaces even if they are more.

    String string = "1-50  of 500+";
    String[] stringArray = string.split("\\s+");
    
    for (String str : stringArray)
    {
        System.out.println(str);
    }
    

    Full example: http://ideone.com/CFVr6N

    EDIT:

    If you also want to split on tabs, change the regex to \\s+|\\t+ and it detects both spaces and tabs as well.

    0 讨论(0)
  • 2021-01-01 03:51

    Use this to spilt the String.

    String[] stringArray = string.split("\\s+");
    
    0 讨论(0)
  • 2021-01-01 03:54
    String[] stringArray = string.split(" +");
    

    instead of

    String[] stringArray = string.split(" ");
    
    0 讨论(0)
  • 2021-01-01 03:55

    You can split using regex

    string.split("\\s+");
    
    0 讨论(0)
提交回复
热议问题