如何知道字符串中特定单词的最后一个索引?(How to know the last index of a particular word in a string?)

优质
小牛编辑
118浏览
2023-12-01

问题描述 (Problem Description)

如何知道字符串中特定单词的最后一个索引?

解决方案 (Solution)

下面的示例演示如何通过使用Pattern类的Patter.compile()方法和Matcher类的matchet.find()方法来了解字符串中特定单词的最后一个索引。

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 last index of Java is: 14

以下是另一个知道字符串中特定单词的最后一个索引的示例。

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main { 
   public static void main(String args[]) {
      String s1 = "Sairamkrishna Mammahe,xnip india Pvt Ltd.";
      Pattern p1 = Pattern.compile("xnip");
      Matcher m1 = p1.matcher(s1);
      m1.find();
      int nextIndex = m1.end();
      System.out.print("The last index is:");
      System.out.println(nextIndex);
   }
}

上面的代码示例将产生以下结果。

The last index is:36