Java - String String Searching

Introduction

You can get the index of a character or a string within another string using the indexOf() and lastIndexOf() methods.

For example,

String str = new String("Apple");

int index;
index = str.indexOf('p');      // index will have a value of 1
index = str.indexOf("pl");     // index will have a value of 2
index = str.lastIndexOf('p');  // index will have a value of 2
index = str.lastIndexOf("pl"); // index will have a value of 2
index = str.indexOf("k");      // index will have a value of -1

indexOf() method starts searching from the start of the string and returns the index of the first match.

lastIndexOf() method searches from the end and returns the index of the first match.

If the character or string is not found in the string, these methods return -1.

Demo

public class Main {
  public static void main(String[] args) {
    String str = new String("Apple");

    int index;/* ww w  . ja  v  a  2  s  .  c  o  m*/
    index = str.indexOf('p');      // index will have a value of 1
    System.out.println(index);
    index = str.indexOf("pl");     // index will have a value of 2
    System.out.println(index);
    index = str.lastIndexOf('p');  // index will have a value of 2
    System.out.println(index);
    index = str.lastIndexOf("pl"); // index will have a value of 2
    System.out.println(index);
    index = str.indexOf("k");      // index will have a value of -1
    System.out.println(index);
  }
}

Result

Exercise