Java Program to find the Last Index of a Particular Word in a String


A String is a sequence of characters. In Java, a string is also an object. It is the object of the String class. The last index of a particular word in a string is nothing but the position of the last occurrence of that word in the string. The index of a character in a string defines or tells the position in the string. The position or Index always starts from 0. In this section, we are going to discuss how to implement a java program to find the last index of a particular word in a string. Strings are immutable in java i.e.; Strings cannot be manipulated. If we manipulate a string a new object will be create.

Examples

Input

searchString = "He is the one and only one male person in our team" word = "one"

Output

The last index is 23

Explanation − In the above example, the word “one” is present at index 10 and at index 23 in the searchString. As, 23 is the last index of the word “one”, the output is 23.

Input

searchString = "Monkey eats banana" word = "eats"

Output

The last index is 7

Explanation − In the above example, the word “eats” is present at index 7 in the searchString. As, 7 is the last index of the word “eats”, the output is 7.

Now, we will discuss various approaches in java to find the last index of a particular word in a String.

Approach 1: Using lastIndexOf() Method

In this approach, we will use the lastIndexOf() in-built method provided by java. String Class and find the last index of a particular word in a string.

Syntax

Below syntax refers to the usage of the method

strobj.lastIndexOf(string)

This method returns last index of a particular string which is given as an input parameter

Algorithm

  • Declare and initialize a String.

  • Initialize the string whose last index we need to find.

  • Use lastIndexOf() method to find the last index of the given word in a given string and store it in a variable.

  • Print the variable value to get the last Index value.

Example

In this example, we initialize a string and word which is to be searched and use the ‘lastIndexOf()’ method. It returns -1 if the input parameter string is not present else if it is present it returns us the last index of occurrence of that string.

// Java program to find lastIndex of a particular word in string.
import java.util.*;
public class Main {
   public static void main(String[] args) {
      String str = "He is the one and only one male person in our team";
      String word = "one";
      int lastindex = str.lastIndexOf(word);
      if (lastindex == -1) {
         System.out.println("The word not present in string.");
      } else {
         System.out.println("The last index of the searched word ==> " + word + " is "+ lastindex);
      }
   }
}

Output

The last index of the searched word ==> one is 23

Approach 2: Using indexOf() Method

In this approach we will use the indexOf() in-built method provided by java.String Class and find the last index of a particular word in a string.

Algorithm

  • Declare and initialize a String.

  • Initialize the word whose last index we need to find.

  • Find the index of the word in the string using indexOf () method which returns the first occurrence of the word and assign it to index variable

  • Using the while loop, assign index to last index and for every index value find the new index of word after the already found index position in the string , using indexOf() method and find this repeatedly until the index value is -1.

  • print the lastindex else print -1.

Example

In the below example, we initialize two variables with strings and use the ‘indexOf()’ method to find the starting index of searching word in the string. After the first index is found repeat this using the while loop but every time you find a new index position you need to update the start_index parameter position in ‘indexOf()’ method with the new index position found. Thus, at last the index values becomes -1 and as in every loop we store the previous index value in lastIndex at last print the lastIndex value.

//java program to find last index of a particular word in a string using indexOf() method
import java.util.*;
public class Main {
   public static void main(String[] args) {
      String str = "He is the one and only one male person in our team";
      String word = "one";
      int lastindex = -1;
      int index = str.indexOf(word);
      while (index != -1) {
         lastindex = index;
         index = str.indexOf(word, index + 1);
      }
      if (lastindex == -1) {
         System.out.println("The word not present in string.");
      } else {
         System.out.println("The last index  is " + lastindex);
      }
   }
}

Output

The last index  is 23

Approach -3: Using regionMatches() Method

In this approach we will use the regionMatches() in-built method provided by java.String Class and find the last index of a particular word in a string.

Syntax

public boolean regionMatches(boolean ignoreCase, int toffset,  String other,  int offset,  int len)

Parameters

  • int offset − The starting index of the region of the first string to be compared.

  • String other − string to compare against.

  • int offset − starting index of the region of the other string to be compared.

  • int len − number of characters to compare.

  • boolean ignoreCase − tells whether to compare with case-insensitive or not. If this parameter value is ‘true’ then it is the comparison is case-insensitive else vice versa.

This method returns true if the specified regions of the two strings match, and false otherwise.

Below example refers to the usage of the method −

String str1 = "Hello, world!";
String str2 = "HELLO, WORLD!";
boolean match1 = str1.regionMatches(0, str2, 0, 12, false); // match1 is false
boolean match2 = str1.regionMatches(true, 0, str2, 0, 12); // match2 is true

Algorithm

  • Initialize a variable str with a string

  • Initialize another variable word with string to be searched and index as -1.

  • Using a for loop, find the index using ‘regionMatches() ’ method and print the value.

Example

In this example, two variables with strings are initialized and a lastIndex variable with -1 is initialized. Then we iterate from last of the string and every time we iterate we check whether the string region matches with the searching string using ‘regionMatches()’ method and if it matches then the method returns true thus we can store the lastIndex value and print the value.

//Java program to find the last index of a particular word in a string
import java.util.*;
public class Main {
   public static void main(String[] args) {
      String str = "Monkey eats banana";
      String word = "eats";   
      int index = -1;
      for(int i = str.length() - word.length(); i >= 0; i--) {
         if(str.regionMatches(i, word, 0, word.length())) {
            index = i;
            break;
         }
      }
      System.out.println("Last index  is " + index);
   }
} 

Output

Last index  is 7

Thus, we in this article have discussed the different approaches to find the last position of a particular word in a string.

Updated on: 16-Aug-2023

121 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements