VOOZH about

URL: https://www.geeksforgeeks.org/java/java-lang-string-lastindexof-method/

⇱ Java String lastIndexOf() Method with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java String lastIndexOf() Method with Examples

Last Updated : 19 Nov, 2024

The String lastIndexOf() method returns the position of the last occurrence of a given character or substring in a String. The Index starts from 0, and if the given substring is not found it returns -1.

In this article, we will learn how to use the string lastIndexOf() method in Java to find the last occurrence of a character or substring in a String.

Program to Find the Last Index of a Character in a String in Java

This program demonstrates how to use the lastIndexOf() method to find the position of the last occurrence of a specified character in a given string.


Output
Found Last Index of l at: 9

Different Ways to Use lastIndexOf() Method in Java

There are four variants of the lastIndexOf() method in Java.

MethodDescription
int lastIndexOf(char ch)It returns the index of the last occurrence of the specified character.
public int lastIndexOf(char ch, int fromIndex)It returns the index of the last occurrence of the specified character, searching backward starting at the specified index.
public int lastIndexOf(String str) It returns the index of the last occurrence of the specified substring.
public int lastIndexOf(String str, int fromIndex)It returns the index of the last occurrence of the specified substring, searching backward starting at the specified index. 

Parameters:

  • ch: Character value to be searched.
  • fromIndex:  index position from where the index of the char value or substring is returned.
  • str: substring to be searched.

Return Value:

  • Last index of char or substring.

Now, lets see examples of all 4 variants of lastIndexOf() method of String class.

Using lastIndexOf(char ch) Method

To demonstrate how to find the last index of a character in a string.


Output
Last index of 'G': 8


Finding the Last Index of a Character Example 

To illustrate the last index of 'g' in a specific string.


Output
Found Last Index of g at: 19


Using lastIndexOf(char ch, int fromIndex) Method

To show how to find the last index of a character, searching backwards from a specified index.


Output
Found Last Index of g at: 11


Using lastIndexOf(String str) Method

To demonstrate how to find the last index of a substring in a string.


Output
Found substring geeks at: 19


Using lastIndexOf(String str, int fromIndex) Method

To show how to find the last index of a substring, searching backwards from a specified index.


Output
Found substring geeks at: 11


Comment