Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Locate Substring in a String in Java



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
Updated on: 2024-06-18T18:39:39+05:30

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements