Java Program to locate a substring in a string

Java 8Object Oriented ProgrammingProgramming

To locate a substring in a string, use the indexOf() method.

Let’s say the following is our string.

String str = "testdemo";

Find a substring ‘demo’ in a string and get the index.

int index = str.indexOf( 'demo');

Example

 Live Demo

public class Demo {
   public static void main(String []args) {
      String str = "testdemo";
      System.out.println("String: "+str);
      int index = str.indexOf("demo");
      System.out.printf("Substring 'demo' is at index %d\n", index);
   }
}

Output

String: testdemo
Substring 'demo' is at index 4
raja
Updated on 27-Jun-2020 06:19:13

Advertisements