Sub topic 6
Searching and Extracting Text
You often need to find part of a string and use it in another part of a program. For example, you might find a separator in "name::Ada" and extract the name after it.
Java’s String class provides methods for these tasks. A method is an action you can call on a value. A search method can tell you whether text is present or where it starts. An extraction method can give you part of the original string.
Positions in a string
An index is a number that identifies a position in a string. Java counts indexes from zero. For this string:
"red, blue, red"
the positions are:
| Index | Text at that index |
|---|---|
| 0 | `r` |
| 1 | `e` |
| 2 | `d` |
| 3 | `,` |
| 4 | a space |
| 5 | `b` |
| 6 | `l` |
| 7 | `u` |
| 8 | `e` |
| 9 | `,` |
| 10 | a space |
| 11 | `r` |
| 12 | `e` |
| 13 | `d` |
Spaces and punctuation count too. This string has a length of 14, so its last index is 13.
For the plain English text in this chapter, each visible character takes one index position. More generally, Java string indexes count UTF-16 code units. A code unit is a piece of Java’s internal text representation. Some characters take two code units, so the number of visible characters is not always the same as the string’s length.
Finding text
The indexOf method finds the first occurrence of text. An occurrence is one place where the searched-for text appears. The method returns the starting index, or -1 if it cannot find the text. To return a value means to give a result back to the caller.
The lastIndexOf method works in much the same way, but finds the last occurrence.
You can also give indexOf a starting position. This tells it where to begin looking. The position itself is included in the search.
Checking whether text is present
The contains, startsWith, and endsWith methods answer yes-or-no questions. Each returns a boolean, a value that is either true or false.
| Method | Question |
|---|---|
| `contains("blue")` | Does the string contain `blue` anywhere? |
| `startsWith("red")` | Does the string begin with `red`? |
| `endsWith("red")` | Does the string end with `red`? |
These methods are useful when you need to know only whether text is present. Use indexOf when you also need its position.
Try the search methods
Save this program in a file named SearchText.java:
class SearchText {
public static void main(String[] args) {
String text = "red, blue, red";
System.out.println(text.indexOf("red"));
System.out.println(text.lastIndexOf("red"));
System.out.println(text.indexOf("red", 1));
System.out.println(text.indexOf("green"));
System.out.println(text.contains("blue"));
System.out.println(text.startsWith("red"));
System.out.println(text.endsWith("red"));
System.out.println(text.contains("Red"));
}
}Compile and run it:
javac SearchText.java
java SearchTextThe output is:
0
11
11
-1
true
true
true
falseThe first red starts at index 0. The last starts at index 11. When the search starts at index 1, it skips the first red, so it finds the one at index 11.
The search for green returns -1 because that text is absent. The final result is false because searches are case-sensitive: uppercase R and lowercase r are different.
An empty search string has a special result. For example, "abc".indexOf("") returns 0. Also, every string starts and ends with the empty string. If an empty search term is not useful in your program, check for it before searching.
Extracting part of a string
A substring is a portion of a string. Java’s substring method returns a new string containing that portion. It does not change the original string.
There are two common forms:
substring(start, end)takes text fromstartup to, but not including,end.substring(start)takes text fromstartthrough the end of the string.
The values passed to a method, such as start and end, are called arguments.
For String text = "red, blue, red";:
| Expression | Result | Reason |
|---|---|---|
| `text.substring(0, 3)` | `"red"` | Takes indexes 0, 1, and 2. |
| `text.substring(5, 9)` | `"blue"` | Takes indexes 5 through 8. |
| `text.substring(11)` | `"red"` | Takes index 11 through the end. |
| `text.substring(4, 4)` | `""` | Start and end are the same, so no text is taken. |
| `text.substring(0, text.length())` | `"red, blue, red"` | Takes the whole string. |
The end index is exclusive: the text at that index is left out. This makes the length of a substring easy to find. For substring(5, 9), the result has length 9 - 5, or 4.
A start index equal to the string’s length is allowed. It produces an empty string because there is no text after that position.
Search first, then extract
A search result is often used as an index for substring. Always check for -1 first. If the search fails, -1 is not a valid substring index.
The following program looks for a separator, the text that marks the boundary between two parts. It extracts everything before the first separator as a label and everything after it as a value.
Save it as ExtractText.java:
class ExtractText {
public static void main(String[] args) {
String[] entries = {"name::Ada", "city::", "missing"};
String separator = "::";
for (String entry : entries) {
int position = entry.indexOf(separator);
if (position == -1) {
System.out.println("No separator in: " + entry);
} else {
String label = entry.substring(0, position);
String value = entry.substring(position + separator.length());
System.out.println("Label: [" + label + "]");
System.out.println("Value: [" + value + "]");
}
}
}
}Compile and run it:
javac ExtractText.java
java ExtractTextThe output is:
Label: [name]
Value: [Ada]
Label: [city]
Value: []
No separator in: missingFor "name::Ada", the separator starts at index 4. The label is substring(0, 4), which stops before the separator. The value starts at index 4 + 2, because the separator has length 2.
Using separator.length() matters. Adding only 1 would leave the second colon at the start of the value.
For "city::", the value starts at the end of the string. That is allowed, so the value is empty. For "missing", the search returns -1; the program reports that result instead of trying to extract text.
This example uses the first separator. If an entry contains another "::", that second separator stays in the value. Whether that is acceptable depends on what your program expects.
Common checks
- Check whether a search returned
-1before using its result as an index. - Remember that
substringleaves out its end index. - Count spaces and punctuation when working out positions.
- Use
containsfor a yes-or-no question andindexOfwhen you need a position. - Check the result if an empty label or value is not allowed. A successful search does not guarantee that both parts contain text.
- Make sure the string you call a method on is not
null. Calling a method onnullcauses an error.
Exercise
For String text = "cat-dog-cat";, what do text.indexOf("cat"), text.lastIndexOf("cat"), and text.substring(4, 7) return?
Show answer
They return 0, 8, and "dog". The substring takes indexes 4, 5, and 6; it leaves out index 7.
Exercise
You search for "::" with int pos = entry.indexOf("::");. How can you safely extract the text after it?
Show answer
First check that pos != -1. Then use entry.substring(pos + 2), or add the separator’s length instead of 2. The result can be empty if the separator is at the end.