Java Arena
Step 4 of 8

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 index start to the end.
  • substring(start, end) gives the characters from start up 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));
Output
pet
car
arp

Because 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("#"));
Output
3
ada
example.com
-1

Three 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"));
Output
true
true
false

All of these count capitals: "Photo.JPG".endsWith(".jpg") is false. When capitals shouldn't matter, make the text small first: file.toLowerCase().endsWith(".jpg").

Your task

Challenge 1 of 3

Fill in the numbers, so the program cuts sun and flower out of sunflower. It prints:

sun
flower

Challenge 2

Read a file name with exactly one dot in it, such as report.pdf, and print the part before the dot and the part after it. For the input report.pdf the program prints:

Name: report
Type: pdf

Challenge 3

Write a method fileKind(String fileName) that returns image for names that end in .jpg or .png, document for names that end in .pdf or .txt, and other for anything else. Capitals don't matter: Beach.JPG is an image. The check runs System.out.println(fileKind("Beach.JPG")); and expects:

image