【发布时间】:2014-03-04 15:09:38
【问题描述】:
我正在尝试在字符串数组中的单词之间拆分空格和破折号。以下代码显示了我追求的结果。
代码:
String[] wordSplit = txtInput.split (" ") && txtInput.split ("-");
输入:
hello world hello-world
预期输出:
there are: 4 word(s) of length 5.
【问题讨论】:
我正在尝试在字符串数组中的单词之间拆分空格和破折号。以下代码显示了我追求的结果。
代码:
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 str = "hello world hello-world";
String[] splitArray = str.split("[-\\s]");
System.out.println("Size of array is :: "+splitArray.length);
输出:4
【讨论】:
您必须在一次拆分中使用更多分隔符。
像这样:
String[]wordSplit = txtInput.split(" |\\-");
【讨论】: