user2095165 user2095165 - 1 month ago 5
Java Question

Split Strings in java by words

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 something like this

String str = "That's the code";

String[] strs = str.split("\\'");
for (String sstr : strs) {
System.out.println(sstr);
}


But the output is

That
s the code

Answer

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);
        }
    }
}