Split Strings in java by words

后端 未结 8 1592
迷失自我
迷失自我 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:59

    You can use OR in regular expression

    public static void main(String[] args) {
        String str = "That's the code";
            String[] strs = str.split("'|\\s");
            for (String sstr : strs) {
                System.out.println(sstr);
            }
       }
    

    The string will be split by single quote (') or space. The single quote doesn't need to be escaped. The output would be

    run:
    That
    s
    the
    code
    BUILD SUCCESSFUL (total time: 0 seconds)
    

提交回复
热议问题