numWords
Category: Programming
Author: Stuart Reges
Book Chapter: 4.3
Problem: numWords
Write a method called numWords that takes a String
as a parameter and that returns the number of words in the String. By
definition, words are separated by one or more spaces. The table below
shows several sample calls and the value that should be returned.
Method Call Value Returned
---------------------------------------------------- --------------
numWords("how many words here?") 4
numWords("to be or not to be, that is the question") 10
numWords(" how about merry-go-round ") 3
numWords(" !&$%--$$!!*() foo_bar_baz ") 2
numWords("x") 1
numWords(" ") 0
numWords("") 0
Notice that words can contain punctuation marks. Any non-empty sequence of
non-space characters can be a word. Also notice that there might be spaces
at the beginning or end of the String.
You may not construct any other objects to solve this problem (e.g., you
can't use a Scanner or tokenizer). You may assume that the String has no
other whitespace characters such as tabs or newline characters. Your method
can pay attention just to spaces to decide how many words there are.