Skip to main content
Logo image

Java, Java, Java: Object-Oriented Problem Solving, 2024E

Section 7.13 Exercises

Exercises String Exercises

Note: For programming exercises, first draw a UML class diagram describing all classes and their inheritance relationships and/or associations.

1. Java Concept Matching.

Exercise Group.

Fill in the blanks.
2. .
When the first character in a string has index 0, this is known as .
3. .
A sequence of characters enclosed within quotes is known as a .

5. Locate Syntax Errors.

Identify the syntax errors in each of the following, assuming that s is the literal string “exercise”:
(a) char at hello.
s.charAt("hello")
(b) index of 10.
s.indexOf(10)
(c) substring er.
s.substring("er")
(d) last index er.
s.lastIndexOf(er)
(e) String length.
s.length

Evaluate String Expressions.

Evaluate each of the following expressions, assuming thats is the literal string “exercise”:
6. .
s.charAt(5)
7. .
s.indexOf("er")
8. .
s.substring(5)
9. .
s.lastIndexOf('e')
10. .
s.length()

Writing String Methods.

Each of the problems that follow asks you to write a method. Of course, as you are developing the method in a stepwise fashion, you should test it. Here’s a simple application program that you can use for this purpose:
public class MethodTester {
    public static String repeat(String s) {
        return s + s;
    }
    public static void main(String args[]) {
        System.out.println("Yo repeated is " + repeat("Yo"));
    }
}
Just replace the repeat() method with your method. Note that you must declare your method static if you want to call it directly from main() as we do here.
11. Code Case Insensitive Equals.
Write your own equalsIgnoreCase() method using only other String methods.
12. Write Strings Equal.
Write your own String equality method without using String.equals() .
Hint.
precedes()
13. Write toLower.
Even though Java’s String class has a built-in toLowerCase() method, write your own implementation of this method. It should take a String parameter and return a String with all its letters written in lowercase.
14. Blocked Text Method.
Write a method that converts its String parameter so that letters are written in blocks five characters long. For example, consider the following two versions of the same sentence:
Plain :   This is how we would ordinarily write a sentence.
Blocked : Thisi showw ewoul dordi naril ywrit easen tence.
15. Document Analysis.
Design and implement a Java Swing program that lets the user type a document into a TextArea and then provides the following analysis of the document: the number of words in the document, the number of characters in the document, and the percentage of words that have more than six letters. In order to test your analysis program, modify the analysis method below so that it takes a string and returns an array of the three numbers computed in the analysis described above.
16. Wordify Single Digit Numbers.
Design and write a Java Swing program that searches for single-digit numbers in a text and changes them to their corresponding words. For example, the string “4 score and 7 years ago” would be converted into “four score and seven years ago”. In order to test your number words program, modify the wordify method below so that it takes a string and returns a new string that has wordified all single digit numbers.
17. Palindrome Tester.
A palindrome is a string that is spelled the same way backward and forward. For example, mom, dad, radar, 727 and able was i ere i saw elba are all examples of palindromes. Write a Java Swing program that lets the user type in a word or phrase and then determines whether the string is a palindrome. In order to test your palindrome tester, modify the isPalindrome method below so that it takes a string and returns true if the string is a palindrome.
18. String To Maze.
Write a maze program that uses a string to store a representation of the maze. Write a method that accepts a String parameter and prints a two-dimensional representation of a maze. For example, the maze shown here, where O marks the entrance and exit can be generated from the following string:
String: XX_XXXXXXXX__XXX_XXXX_XX____XXX_XX_XX_XXX____X____XXXXXXXX_X
  O
XX XXXXXXX
X  XXX XXX
X XX    XX
X XX XX XX
X    X    O
XXXXXXXX X
19. Mailing Label.
Write a method that takes a delimited string to store a name and address, from which you can print a mailing label. For example, if the string contains “Sam Penn:14 Bridge St.:Hoboken, NJ 01881,” the method should print the label shown in the margin. {1pt} Sam Penn 14 Bridge St. Hoboken, NJ 01881 __________ }
20. Time Bomb Game.
Design and implement a Java Swing program that plays Time Bomb with the user. Here’s how the game works. The computer picks a secret word and then prints one asterisk for each letter in the word: * * * * *. The user guesses at the letters in the word. For every correct guess, an asterisk is replaced by a letter: * e * * *. For every incorrect guess, the time bomb’s fuse grows shorter. When the fuse disappears, after say, six incorrect guesses, the bomb explodes. Store the secret words in a delimited string and invent your own representation for the time bomb. To test your replacement algorithm modify the method disclose that takes the *’d word, the correct word and the letter guessed and returns a modified *’d word with any correct letters put in the right place of the *’d word.
21. Global Replace Program.
Challenge: The global replace function is a string-processing algorithm found in every word processor. Write a method that takes three String arguments: a document, a target string, and a replacement string. The method should replace every occurrence of the target string in the document with the replacement string. For example, if the document is “To be or not to be, that is the question,” and the target string is “be,”, and the replacement string is “see,” the result should be, “To see or not to see, that is the question.”

22. Secret Letter Game.

Challenge: Design and implement a Java Swing Program that plays the following game with the user. Let the user pick a letter between A and Z. Then let the computer guess, the secret letter. For every guess the player has to tell the computer whether it’s too high or too low. The computer should be able to guess the letter within five guesses. Do you see why?

23. String Backed List.

Challenge: A list is a sequential data structure. Design a List class that uses a comma-delimited String — such as, “a,b,c,d,12,dog” — to implement a list. Implement the following methods for this class:
void addItem( Object o );      // Use Object.toString()
String getItem(int position);
String toString();
void deleteItem(int position);
void deleteItem(String item);
int getPosition(String item);
String getHead();              // First element
List getTail();                // All but the first element
int length();                  // Number of items

24. String Backed Directory.

Challenge: Use a delimited string to create a PhoneList class with an instance method to insert names and phone numbers, and a method to look up a phone number when a user provides a person’s name. Since your class will take care of looking things up, you don’t have to worry about keeping the list in alphabetical order. For example, the following string could be used as such a directory:
mom:860-192-9876::bill g:654-0987-1234::mary lancelot:123-842-1100

25. Message Display.

Design and implement an application that displays a multi-line message in various fonts and sizes input by the user. Let the user choose from among a fixed selection of fonts, sizes, and styles.
You have attempted of activities on this page.