Here's a different way of looking at it, and it's a simple one-liner:
int spaces = s.replaceAll("[^ ]", "").length();
This works by effectively removing all non-spaces then taking the length of what’s left (the spaces).
You might want to add a null check:
int spaces = s == null ? 0 : s.replaceAll("[^ ]", "").length();
You can use a stream too:
int spaces = s.chars().filter(c -> c == (int)' ').count();