- Java 编程示例
- 示例 - Home
- 示例 - Environment
- 示例 - 字符串
- 示例 - 数组
- 示例 - 日期和时间
- 示例 - 方法
- 示例 - 文件
- 示例 - 目录
- 示例 - 异常
- 示例 - 数据结构
- 示例 - 集合
- 示例 - 网络
- 示例 - 线程
- 示例 - 小程序
- 示例 - 简单 GUI
- 示例 - JDBC
- 示例 - 正则表达式
- 示例 - Apache PDF 文档
- 示例 - Apache POI PPT
- 示例 - Apache POI Excel
- 示例 - Apache POI Word
- 示例 - OpenCV
- 示例 - Apache Tika
- 示例 - iText
- Java 教程
- Java - 教程
- 有用的 Java 资源
- Java - 快速指南
- Java - 有用的资源
如何使用 Java 查找字符串中特定单词的最后一个索引
问题描述
如何在字符串中查找特定单词的最后一个索引?
解决方案
以下示例演示如何通过使用 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);
}
}
结果
上述代码示例将产生以下结果。
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,Tutorialspoint india Pvt Ltd.";
Pattern p1 = Pattern.compile("Tutorialspoint");
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
java_regular_exp.htm
广告