10. Strings and String Processing

10.1. Introduction

 

You have already had an introduction to Strings in the early chapters of this text. In Chapter 2, we introduced the String data type and showed how to create String objects and use String methods, such as length(), concat(), and equals().

We have seen Strings used for GUI I/O operations when used Strings as the contents of JTextFields and other text components, as the values of JLabels, as the labels for JButtons, and so on. Strings are also used extensively in command-line interfaces.

Another important task that Strings are used for are as a standard way of presenting or displaying information about objects. As we saw in Chapter 2, one of the key conventions of the Java class hierarchy is that every class inherits the Object.toString() method, which can be used to provide a string representation of any object. For example, Integer.toString() converts an int to a String, so that it can be used in JTextFields or JLabels.

Programmers often have to work with strings. Think of some of the

tasks performed by a typical word processor, such as cut, paste, copy, and insert. When you cut and paste text from one part of the document to another, the program has to move one string of text, the cut, from one location in the document and insert it in another.

Strings are also important because they are our first look at a data struc- ture. A data structure is a collection of data that is organized (structured) in some way. A string is a collection of character (char) data. Strings are important data structures in a programming language, and they are used to represent a wide variety of data.

The main purpose of this chapter is to provide a detailed discussion of Java’s string-related classes, including the String, StringBuffer, and StringTokenizer classes. These are the important classes for writing string-processing applications. Our goal is to introduce the important

String methods and illustrate common string-processing algorithms.

We will review how to create strings from scratch and from other data

 

Figure7.1:The

java.lang.Stringclass.

 

 

 

 

 

 

 

 

 

 

Are strings objects?


types. We will learn how to find characters and substrings inside bigger strings. We will learn how to take strings apart and how to rearrange their parts. Finally, we will learn how to apply these string-processing skills in a program that plays the game of Hang Man.