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


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

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements