How to know the last index of a perticular word in a string?
Solution:
Following example demonstrates how to know the last index of a perticular word in a string by using Patter.compile() method of Pattern class and matchet.find() method of Matcher class.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String args[]) {
String candidateString = "This is a Java example.
This is another Java example.";
Pattern p = Pattern.compile("Java");
Matcher matcher = p.matcher(candidateString);
matcher.find();
int nextIndex = matcher.end();
System.out.print("The last index of Java is:");
System.out.println(nextIndex);
}
}
Result:
The above code sample will produce the following result.