Sub topic 6
Searching and Extracting Text
You can search a Java string to find text, then extract the part you need. For example, if a string contains name=Ada Lovelace, you can find the = sign and take the text after it.
Find text with indexes
An index is a number that marks a position in a string. The first position is 0, not 1.
In name=Ada, the = is at index 4:
| Text | n | a | m | e | = | A | d | a |
|---|---|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
A method is an action you can ask an object to perform. The indexOf method searches for text and returns its starting index. If it cannot find the text, it returns -1.
For example, with String text = "name=Ada Lovelace";:
| Expression | Result | Meaning |
|---|---|---|
| `text.indexOf("Ada")` | `5` | `Ada` starts at index `5`. |
| `text.indexOf("Grace")` | `-1` | `Grace` is not present. |
| `text.indexOf("a")` | `1` | This is the first lowercase `a`. |
| `text.lastIndexOf("a")` | `14` | This is the last lowercase `a`. |
| `text.contains("Ada")` | `true` | The string contains `Ada`. |
Searches are case-sensitive: uppercase A and lowercase a are different. You can also use startsWith and endsWith to test the beginning or end of a string. These methods return true or false.
Extract a substring
A substring is a part of a string. The substring method creates a new string from the part you choose. It does not change the original string.
The call text.substring(start, end) includes the character at start but stops before end. For example, text.substring(5, 8) returns Ada: it takes indexes 5, 6, and 7.
You can leave out the end index to take everything from the start index to the end of the string. For example, text.substring(5) returns Ada Lovelace.
Worked example
Save this program as SearchText.java, then run javac SearchText.java followed by java SearchText.
class SearchText {
public static void main(String[] args) {
String text = "name=Ada Lovelace";
int separator = text.indexOf("=");
if (separator >= 0) {
String label = text.substring(0, separator);
String value = text.substring(separator + 1);
System.out.println(label);
System.out.println(value);
}
int start = text.indexOf("Ada");
if (start >= 0) {
System.out.println(text.substring(start, start + "Ada".length()));
}
System.out.println(text.indexOf("Grace"));
System.out.println(text.contains("Lovelace"));
}
}The output is:
name
Ada Lovelace
Ada
-1
trueThe program checks each search result before using it. For the label, it stops at the = index, so the result leaves out =. For the value, it starts one position after =.
Indexes count UTF-16 code units, not always whole visible characters. For the letters and symbols in this example, each one takes one position.
Exercise
If text is "red,blue", what does text.substring(0, text.indexOf(",")) return?
Show answer
It returns "red". The comma is at index 3, and the end index is not included.