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: 2020-06-26T15:28:38+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started