我想分割字符串數組中的單詞之間的空格和破折號字符。下面的代碼顯示了我之後的結果。將字符串拆分爲僅用於空格或短劃線。 Java小程序
代碼:
String[] wordSplit = txtInput.split (" ") && txtInput.split ("-");
輸入:
hello world hello-world
預期輸出:
there are: 4 word(s) of length 5.
我想分割字符串數組中的單詞之間的空格和破折號字符。下面的代碼顯示了我之後的結果。將字符串拆分爲僅用於空格或短劃線。 Java小程序
代碼:
String[] wordSplit = txtInput.split (" ") && txtInput.split ("-");
輸入:
hello world hello-world
預期輸出:
there are: 4 word(s) of length 5.
使用字符集([..]
);它匹配列出的字符之一。
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
使用字符類:
String[] wordSplit = txtInput.split("[ -]");
你必須在一個分割使用更多的分隔符。
像這樣:下面的代碼
String[]wordSplit = txtInput.split(" |\\-");
用途:
String str = "hello world hello-world";
String[] splitArray = str.split("[-\\s]");
System.out.println("Size of array is :: "+splitArray.length);
輸出:4
這有什麼錯呢? – devnull