Java Data Type Tutorial - Java String Search








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");
/*ww  w  . ja  v a  2s . 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.





Matching Start and End of a String

The startsWith() checks if the string starts with the specified argument, whereas endsWith() checks if the string ends with the specified string argument.

Both methods return a boolean value.

public class Main {
  public static void main(String[] args) {
    String str = "This is a test";
//  w w  w.java 2  s .  c om
    // Test str, if it starts with "This"
    if (str.startsWith("This")) {
      System.out.println("String starts with  This");
    } else {
      System.out.println("String does  not  start with  This");
    }

    // Test str, if it ends with "program"
    if (str.endsWith("program")) {
      System.out.println("String ends  with  program");
    } else {
      System.out.println("String does  not  end  with  program");
    }

  }
}

The code above generates the following result.