Search index of a character in a string in Java


Use the indexOf() method to search the index of a character in a string.

Let’s say the following is our string.

String myStr = "amit";

Now, let us find the index of character ‘t’ in the above string.

strIndex = myStr.indexOf('t');

The following is the final example.

Example

 Live Demo

public class Demo {
    public static void main(String[] args) {
       String myStr = "amit";
       int strIndex = 0;
       System.out.println("String: "+myStr);
       // finding index of character t
       strIndex = myStr.indexOf('t');
       System.out.println("Character m found at index: "+strIndex);
    }
}

Output

String: amit
Character m found at index: 3

Updated on: 26-Jun-2020

918 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements