Reputation: 13
String[] t = a.slowa("a. R; er, we p.");
for (String w : t)
System.out.println(w);
}
//...
public String[] slowa(String s) {
return s.split(" |\\.|,|\\;");
}
output:
a
R
er
we
p
Why spaces are new world?
Upvotes: 1
Views: 1340
Reputation: 1074949
You've told the String#split
function to split on a space or a dot or a comma or a semicolon. So that's what it's done:
"a. R; er, we p."
^^ ^^ ^^^ ^ ^
|| || ||| | |
|| || ||| | +--Split here
|| || ||| +----And here
|| || ||+-------And here
|| || |+--------And here
|| || +---------And here
|| |+------------And here
|| +-------------And here
|+---------------And here
+----------------And here
...because you've used an alternation with no quantifier. What you want is to say split on any of these:
return s.split("[ .,;]+");
That uses a character class ([...]
) and a quanitifier (+
) so that more than one in a row is treated as a single match. You could also do it with an alternation+quantifier (you have to wrap the alternation in a non-capturing group: "(?: |\\.|,|\\;)+"
), but using a character class is cleaner.
Upvotes: 7