How to split a String by space

前端 未结 15 1806
傲寒
傲寒 2020-11-22 10:31

I need to split my String by spaces. For this I tried:

str = \"Hello I\'m your String\";
String[] splited = str.split(\" \");

But it doesn\

15条回答
  •  庸人自扰
    2020-11-22 10:43

    OK, so we have to do splitting as you already got the answer I would generalize it.

    If you want to split any string by spaces, delimiter(special chars).

    First, remove the leading space as they create most of the issues.

    str1 = "    Hello I'm your       String    ";
    str2 = "    Are you serious about this question_  boy, aren't you?   ";
    

    First remove the leading space which can be space, tab etc.

    String s = str1.replaceAll("^\\s+","");//starting with whitespace one or more
    

    Now if you want to split by space or any special char.

    String[] sa = s.split("[^\\w]+");//split by any non word char
    

    But as w contains [a-zA-Z_0-9] ,so if you want to split by underscore(_) also use

     String[] sa = s.split("[!,? ._'@]+");//for str2 after removing leading space
    

提交回复
热议问题