仅按空格或破折号拆分字符串。Java Applet

4
我是一位能够翻译文本的助手。
我正在尝试在字符串数组中分割空格和破折号。以下代码展示了我想要的结果:
代码:
String[] wordSplit = txtInput.split (" ") && txtInput.split ("-");

输入:

hello world hello-world

期望输出:

there are: 4 word(s) of length 5.
4个回答

7
使用字符集([..]);它匹配列表中列出的任意一个字符。
String[] wordSplit = txtInput.split("[-\\s]")

例子:

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

输出:

hello
world
hello
world

1
使用一个字符类:
String[] wordSplit = txtInput.split("[ -]");

1

Use below code :

        String str = "hello world hello-world";
        String[] splitArray = str.split("[-\\s]");
        System.out.println("Size of array is :: "+splitArray.length);

输出: 4

0

你必须在一个分割中使用更多的分隔符。
像这样:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接