Searching and Comparing Strings
Finding text with indexOf
A photo app keeps each picture's file name.
String file = "beach_day.jpg";
The call
file.indexOf(".") returns 9, the index where the dot is. The argument can be more than one character: file.indexOf("day") returns 6, the index where that text starts. When the text appears more than once, the first occurrence counts, so file.indexOf("a") returns 2, from the "a" in "beach".When the text isn't there at all,
indexOf returns -1. So file.indexOf("png") is -1. No index is negative, so -1 can't be confused with a real position.Using the index
An index from
indexOf can be passed to substring. The app also stores where each photo was taken, as a place and a state with a comma and a space between them.String place = "Lake Erie, Ohio";
int sep = place.indexOf(", ");
String lake = place.substring(0, sep);
String state = place.substring(sep + 2);
Here
sep is 9, the index of the comma. The first substring stops before index 9, so lake is "Lake Erie". The separator is two characters long, so the state starts two past it, at index 11, and state is "Ohio".A label with no separator breaks this. For
"Yosemite", indexOf(", ") returns -1, and substring(0, -1) throws a StringIndexOutOfBoundsException.equals
The app shows a preview only for JPEG files.
String kind = file.substring(10);
boolean preview = kind.equals("jpg");
The extension starts at index 10, just after the dot, so
kind is "jpg". Then preview is true, since kind and "jpg" hold an identical sequence of characters. The comparison is exact, capital letters included. For a file named "cliff.JPG", the extension is "JPG", and "JPG".equals("jpg") is false.compareTo
The app lists file names in order, and
compareTo tells it which name comes first.int c = file.compareTo("canyon.jpg");The value of
c is negative. The letter b is earlier in the alphabet than c, so the beach photo is listed first. Reversed, "canyon.jpg".compareTo(file) is positive, and a name compared with an identical name gives 0. A program uses only whether the result is negative, zero, or positive.The names are compared character by character until two differ, and the one with the earlier character comes first. When one string runs out first, as in
"beach".compareTo("beach_day"), the shorter one comes first, so that value is negative too. Capitals are placed ahead of all lowercase letters in this ordering, so "Zoo".compareTo("ant") is negative.