Java Data Type How to - Search a String








Question

We would like to know how to search a String.

Answer

We can get the index of a character or a string within another string using the indexOf() and lastIndexOf() methods. For example,

public class Main {
  public static void main(String[] args) {
    String str = new String("Apple");
//  w  ww .  j a  v a 2 s .  co m
    int 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);
  }
}

The code above generates the following result.

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

The lastIndexOf() method matches the character or the string 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.