2014-03-04 18 views

回答

6

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

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("[ -]"); 
+3

這有什麼錯呢? – devnull

0

你必須在一個分割使用更多的分隔符。
像這樣:下面的代碼

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

用途:

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

輸出:4