Sub topic 2
Searching and Extracting Text
To try the examples, start jshell in a terminal. JShell is a tool for trying Java code one piece at a time. Enter the blocks in order in the same session. JShell may show extra feedback; the results described below are from the println calls.
Searching and Extracting Text
An index is a position in a string. In "red,blue", the first letter has index 0, and b has index 4.
A method is an action you can call on a value. The indexOf method searches for text and returns its starting index. It returns -1 if the text is not found.
String text = "red,blue";
int start = text.indexOf("blue");
if (start != -1) {
System.out.println(start);
System.out.println(text.substring(start, start + 4));
}This prints 4 and then blue. The substring method extracts part of a string. Its first index is included, but its end index is excluded. Here, it takes indexes 4 through 7.
Check for -1 before using a search result as an index. Also make sure the end index is not beyond the string’s length.
Creating Transformed Strings
Strings are immutable: once created, their contents cannot change. Methods that transform text return a string with the result.
String clean = " blue ".trim();
String changed = clean.replace("blue", "green");
System.out.println(clean);
System.out.println(changed);This prints blue and then green. The trim method removes space from the ends. The replace method replaces matching text. It does not change clean.
Combining Strings
The + operator joins strings. This is called concatenation.
String greeting = "Hello, " + clean + "!";
System.out.println(greeting);This prints Hello, blue!. Remember to add any spaces or punctuation you need.
Building Strings Efficiently
For many additions in a loop, use a StringBuilder, an object that lets you build text by changing its contents. Its append method adds to the end. When finished, call toString to get a string.
StringBuilder builder = new StringBuilder();
for (int i = 1; i <= 3; i++) {
if (i > 1) {
builder.append(", ");
}
builder.append(i);
}
String result = builder.toString();
System.out.println(result);This prints 1, 2, 3. Unlike a string, the builder can be changed as the loop runs.
Exercise
For the string "red,blue", what do indexOf("blue") and substring(4, 8) return?
Show answer
They return 4 and "blue". The end index 8 is excluded.
Exercise
Why use StringBuilder when adding many pieces of text in a loop?
Show answer
It lets you add pieces to a changeable builder, then create the final string with toString.