Java Program to locate a character in a string


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

Let’s say the following is our string.

String str = "testdemo";

Find a character ‘d’ in a string and get the index.

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

Example

 Live Demo

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

Output

String: testdemo
'd' is at index 4

Let us see another example. The method returns -1, if the character isn’t found −

Example

 Live Demo

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

Output

String: testdemo
'h' is at index -1

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 27-Jun-2020

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements