Home  >  Article  >  Java  >  Java program to find the last index of a specific word in a string

Java program to find the last index of a specific word in a string

WBOY
WBOYforward
2023-09-17 18:01:021310browse

Java program to find the last index of a specific word in a string

A string is a sequence of characters. In Java, a string is also an object. It is an object of String class. The last index of a particular word in a string is nothing more than 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 will discuss how to implement a java program to find the last index of a specific word in a string. Strings are immutable in Java, i.e. they cannot be manipulated. If we operate on a string, a new object is created.

Example

enter

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" appears at index 10 and index 23 in the search string. Since 23 is the last index of the word "one", the output is 23.

enter

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

Output

The last index is 7

Explanation - In the above example, the word "eats" appears at index 7 of the search string. Since 7 is the last index of the word "eats", the output is 7.

Now, we will discuss the various methods in Java to find the last index of a specific word in a string.

Method 1: Use lastIndexOf() method

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

grammar

The following syntax refers to the usage of this method

strobj.lastIndexOf(string)

This method returns the last index of a specific string given as an input parameter

algorithm

  • Declare and initialize a string.

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

  • Use the lastIndexOf() method to find the last index of a 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 the string and word to search for and use the "lastIndexOf()" method. If the input parameter string does not exist, -1 is returned; if it exists, the index of the last occurrence of the string is returned.

// 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

Method 2: Use indexOf() method

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

algorithm

  • Declare and initialize a string.

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

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

  • Use a while loop, assign the index to the last index and for each index value find the new index of the word after the already found index position in the string, use the indexOf() method and repeat the search until the index The value is -1.

  • Print the last index, otherwise print -1.

Example

In the following example, we initialize two variables with strings and use the 'indexOf()' method to find the starting index of the search word in the string. Once the first index is found, repeat this using a while loop, but each time a new index position is found, the start_index parameter position in the "indexOf()" method needs to be updated with the new index position found. So at the end the index value becomes -1 and in each loop we store the previous index value in lastIndex and finally 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

Method-3: Use regionMatches() method

In this method, we will use the RegionMatches() built-in method provided by the java.String class and find the last index of a specific word in the string.

grammar

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

parameter

  • int offset - The starting index of the first string range to compare.

  • String other - The string to compare.

  • int offset - The starting index of another string range to compare.

  • int len - The number of characters to compare.

  • booleanignoreCase - Tells whether comparisons should be made case-insensitively. If this parameter value is "true", the comparison is case-insensitive, otherwise vice versa.

If the specified areas of the two strings match, this method returns true, otherwise it returns false.

The following example refers to the usage of this 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 the variable str

  • with a string
  • Initialize another variable word with the string to be searched, and the index is -1.

  • Using a for loop, use the "regionMatches()" method to find the index and print the value.

示例

在此示例中,初始化了两个带有字符串的变量,并初始化了一个带有 -1 的 lastIndex 变量。然后我们从字符串的最后一个开始迭代,每次迭代时,我们使用“regionMatches()”方法检查字符串区域是否与搜索字符串匹配,如果匹配,则该方法返回 true,因此我们可以存储 lastIndex 值并打印值。

//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);
   }
} 

输出

Last index  is 7

因此,我们在本文中讨论了查找字符串中特定单词的最后位置的不同方法。

The above is the detailed content of Java program to find the last index of a specific word in a string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete