Finding parts of a string
substring cuts a piece out of a string. Like every String method, it gives back a new string and leaves the original whole.
substring(start)gives everything from the indexstartto the end.substring(start, end)gives the characters fromstartup to, but not including,end.
| Index | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
"carpet" |
c | a | r | p | e | t |
String word = "carpet";
System.out.println(word.substring(3));
System.out.println(word.substring(0, 3));
System.out.println(word.substring(1, 4));
pet
car
arpBecause the end isn't included, substring(start, end) is always end - start characters long: substring(1, 4) has 3. An index past the end crashes the program with the same StringIndexOutOfBoundsException as charAt.
Searching in a string
indexOf looks for a piece of text and returns the index where it first starts, or -1 when it isn't there. Together with substring, it cuts a string at a certain character, wherever that character happens to be:
String email = "ada@example.com";
int at = email.indexOf("@");
System.out.println(at);
System.out.println(email.substring(0, at));
System.out.println(email.substring(at + 1));
System.out.println(email.indexOf("#"));
3
ada
example.com
-1Three more methods answer yes-or-no questions with a boolean:
String file = "holiday-photo.jpg";
System.out.println(file.contains("photo"));
System.out.println(file.startsWith("holiday"));
System.out.println(file.endsWith(".png"));
true
true
falseAll of these count capitals: "Photo.JPG".endsWith(".jpg") is false. When capitals shouldn't matter, make the text small first: file.toLowerCase().endsWith(".jpg").