在空格上拆分字符串或仅划线.Java Applet

car*_*ruk 3 java regex applet split

我正在尝试在字符串数组中的单词之间拆分空格和短划线字符.以下代码显示了我之后的结果.

码:

String[] wordSplit = txtInput.split (" ") && txtInput.split ("-");
Run Code Online (Sandbox Code Playgroud)

输入:

hello world hello-world
Run Code Online (Sandbox Code Playgroud)

预期产量:

there are: 4 word(s) of length 5.
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 7

使用字符集([..]); 它匹配列出的字符之一.

String[] wordSplit = txtInput.split("[-\\s]")
Run Code Online (Sandbox Code Playgroud)

例:

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

输出:

hello
world
hello
world
Run Code Online (Sandbox Code Playgroud)