Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string on whitespace OR dash only. Java Applet

I'm trying to split a space AND a dash character between words in a string array. The following code shows what kind of result I am after.

Code:

String[] wordSplit = txtInput.split (" ") && txtInput.split ("-");

input:

hello world hello-world

expected output:

there are: 4 word(s) of length 5.
like image 705
carteruk Avatar asked Jan 12 '23 02:01

carteruk


2 Answers

Use set of characters([..]); it matches one of character listed.

String[] wordSplit = txtInput.split("[-\\s]")

Example:

class T {
    public static void main(String[] args) {
        String[] words = "hello world hello-world".split("[-\\s]");
        for (String word : words) {
            System.out.println(word);
        }
    }
}

output:

hello
world
hello
world
like image 167
falsetru Avatar answered Jan 16 '23 00:01

falsetru


Use a character class:

String[] wordSplit = txtInput.split("[ -]");
like image 36
devnull Avatar answered Jan 15 '23 22:01

devnull