public static int countWords(String s)Note: This is declared
static
because it is doesn't depend on
instance variables from the class it is defined in.
It's declared public
only because
it might be generally useful.
Call | Returns | Comments |
---|---|---|
countWords("Hello") | 1 | One word. |
countWords("Hello world") | 2 | Two word. |
countWords("Hello, world.") | 2 | Still two words. |
countWords("Don't worry?") | 3 | Three words because of the single quote. |
countWords("Easy as 123, . . .") | 2 | Two words. |
Character.isLetter()
).
If an alphabetic character is encountered when you're outside a word,
then you should increase the word count and switch the state of the
boolean variable.