College Board Unit 1
How it works
The call substring(a, b) returns characters from index a up to but not including index b, so the result has b - a characters. The one-argument form substring(a) runs from index a to the end of the String. The indexOf method returns the index of the first occurrence of a target, or -1 when the target does not appear at all.
Mark both boundaries on paper before evaluating, and handle the not-found case explicitly.
Common error
Treating the end index as inclusive, which produces a string one character too long.
Worked example
Java
String text = "red-blue";
int dash = text.indexOf("-");
System.out.println(text.substring(0, dash));
System.out.println(text.substring(dash + 1));Output
red
blueThe delimiter is at index 3; excluding it from both slices splits the text.
Exercises
4.2.1 · Trace
Determine the exact output. Explain the Java rule or state changes that produce it.
Java
String text = "banana";
System.out.println(text.indexOf("ana"));
System.out.println(text.substring(2, 5));Show solution
Output
1
nanindexOf finds the first occurrence, and substring(2, 5) uses indices 2, 3, and 4.
4.2.2 · Write code
Write public static String beforeColon(String text). Return the portion before the first colon, or the entire String if no colon occurs.
Show solution
One valid solution is shown below. Other implementations satisfying the contract are also valid.
Java
public static String beforeColon(String text) {
int index = text.indexOf(":");
if (index == -1) return text;
return text.substring(0, index);
}Check your code
Java
System.out.println(beforeColon("key:value"));
System.out.println(beforeColon("plain"));
System.out.println("[" + beforeColon(":value") + "]");Expected output
key
plain
[]