【问题标题】:Split string on whitespace OR dash only. Java Applet仅在空格或破折号上拆分字符串。 Java 小程序
【发布时间】:2014-03-04 15:09:38
【问题描述】:

我正在尝试在字符串数组中的单词之间拆分空格和破折号。以下代码显示了我追求的结果。

代码:

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

输入:

hello world hello-world

预期输出:

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

【问题讨论】:

    标签: java regex split applet


    【解决方案1】:

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

    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
    

    【讨论】:

      【解决方案2】:

      使用字符类:

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

      【讨论】:

        【解决方案3】:

        使用下面的代码:

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

        输出:4

        【讨论】:

          【解决方案4】:

          您必须在一次拆分中使用更多分隔符。
          像这样:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-10-19
            • 1970-01-01
            • 1970-01-01
            • 2016-05-09
            • 1970-01-01
            相关资源
            最近更新 更多