Task 10 of 15 · 0 solved · 15 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

1.5 Strings — finding text inside a string

Lesson

Where does it occur?

indexOf searches for a piece of text and returns the position where it first appears. If the text is not there at all, it returns -1 — a value chosen precisely because it is not a valid position.


Worked example

String w = "programming";
System.out.println(w.indexOf("gram"));   // 3
System.out.println(w.indexOf("m"));      // 6  — the FIRST m
System.out.println(w.indexOf("z"));      // -1 — not found

Combined with substring this becomes useful: find where something starts, then cut from there.


▶ Try it: run this, then change something and run it again.



indexOf returns -1 when...


If the text occurs twice, indexOf returns...


Type exactly what this program prints.

public class Main { public static void main(String[] a){
    String s = "banana";
    System.out.println(s.indexOf("na"));
    System.out.println(s.indexOf("x"));
}}

Why is -1 used for «not found»?


True or false?