Search index of a character in a string in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 12-Dec-2018 14:02:35
Advertisements