Ask Questions?

View Latest Questions

Advertisement


 
 

Exercise - Count Words
Posted on: July 26, 2006 at 12:00 AM
Write a method which counts the number of words in a string. Assume that a word is defined as a sequence of letters.

Java: Exercise - Count Words

Problem

Write a method which counts the number of words in a string. Assume that a word is defined as a sequence of letters.

Signature

    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.

Example

CallReturnsComments
countWords("Hello")1One word.
countWords("Hello world")2Two word.
countWords("Hello, world.")2Still two words.
countWords("Don't worry?")3Three words because of the single quote.
countWords("Easy as 123, . . .")2Two words.

Hints

One way to solve this is to go down the string one character at a time. Use a boolean variable to indicate whether you're in a word or not. When the variable indicates that you're in a word, you can ignore alphabetic characters (tested with 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.

Extensions

A better definition of "word" would make this better. For example, non-alphabetics between words should only count if they include at least one blank so that contractions like "don't" aren't counted as two words.

Assumptions

Write only the method. You can easily change the Example - Generic Calc program to use this method.
Copyleft 2003 Fred Swartz MIT License, Last update: 2003-11-23
Advertisement


DMCA.com