String ciag="Hello My name is Tomek, i am from Mars.";
String[] words = ciag.replaceAll("[,.]", "").split("\\s+");
Testing:
System.out.println(Arrays.asList(words).toString());
Output:
[Hello, My, name, is, Tomek, i, am, from, Mars]
Explanation:
[,.]
Is a regular expression. The []
is a character class, meaning that the regex will match any character inside the brackets. So [,.]
means match a comma or a full stop. Any match for this character class will be replaced with an empty String replaceAll("[,.]", "")
, so as a result of this, all commas and full stops are removed.
After the replacing is completed, we then split the resulting String with another regular expression \\s+
which matches one or more whitespace. So split("\\s+")
will split the String into words.