The Practice and Philosophy of Object-Oriented Programming in Java

New Practice Problems for Chapter 5

Word Compression. Write a program that prompts the user to enter a word and outputs the result of compressing that word according to the following rule. Suppose the first character of the word occurs at least twice. The sequence of characters between the first character and the next occurrence of that character is replaced by the length of that sequence. For example, blueberries becomes b3berries. However, the length of the sequence must be at least two. If the length is less than two, or if the first character occurs only once, then the word is compressed simply by removing the first character:

Enter a word: blueberries
Compressed: b3berries
Enter a word: cranberries
Compressed: ranberries
Enter a word: raspberries
Compressed: r5rries
Enter a word: strawberries
Compressed: s10s