Split Strings in java by words

后端 未结 8 1590
迷失自我
迷失自我 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 split by a regex that would be one of the two characters - quote or space:

    String[] strs = str.split("['\\s]");
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题