A solution using java.util.regex.Pattern / java.util.regex.Matcher
String test = "foo bar baz ";
Pattern pattern = Pattern.compile(" ");
Matcher matcher = pattern.matcher(test);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println(count);