Split Strings in java by words

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

    To specifically split on white space and the apostrophe:

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

    or to split on any non word character:

    public class Split {
        public static void main(String[] args) {
            String [] tokens = "That's the code".split("[\\W]");
            for(String s:tokens){
                System.out.println(s);
            }
        }
    }
    

提交回复
热议问题