Split Strings in java by words

后端 未结 8 1609
迷失自我
迷失自我 2020-12-16 06:06

How can I split the following word in to an array

That\'s the code

into

array
0 That
1 s
2 the
3 code

I tried

8条回答
  •  失恋的感觉
    2020-12-16 06:42

    split uses regex and in regex ' is not special character so you don't need to escape it with \. To represent whitespaces you can use \s (which in String needs to be written as "\\s"). Also to create set of characters you can use "OR" operator | like a|b|c|d, or just use character class [abcd] which means exactly the same as (a|b|c|d).

    To makes things simple you can use

    String[] strs = str.split("'| ");
    

    or

    String[] strs = str.split("'|\\s");//to include all whitespaces
    

    or

    String[] strs = str.split("['\\s]");//equivalent of "'|\\s"
    

提交回复
热议问题