Finding the last occurrence of a character in a String in Java

Java 8Object Oriented ProgrammingProgramming

Use the lastIndexOf() method to find the last occurrence of a character in a string in Java.

Let’s say the following is our string.

String myStr = "Amit Diwan";

In the above string, we will find the last occurrence of character ‘i’

myStr.lastIndexOf('i');

The following is the complete example.

Example

 Live Demo

public class Demo {
 public static void main(String[] args) {
    String myStr = "Amit Diwan";
    int strLastIndex = 0;
    System.out.println("String: "+myStr);
    strLastIndex = myStr.lastIndexOf('i');
    System.out.println("The last index of character a in the string: "+strLastIndex);
 }
}

Output

String: Amit Diwan
The last index of character a in the string: 6
raja
Published on 12-Dec-2018 10:06:54
Advertisements