I'm trying to split a space AND a dash character between words in a string array. The following code shows what kind of result I am after.
Code:
String[] wordSplit = txtInput.split (" ") && txtInput.split ("-");
input:
hello world hello-world
expected output:
there are: 4 word(s) of length 5.
Use set of characters([..]
); it matches one of character listed.
String[] wordSplit = txtInput.split("[-\\s]")
Example:
class T {
public static void main(String[] args) {
String[] words = "hello world hello-world".split("[-\\s]");
for (String word : words) {
System.out.println(word);
}
}
}
output:
hello
world
hello
world
Use a character class:
String[] wordSplit = txtInput.split("[ -]");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With