如何在 Java 中搜索子字符串的最后一个位置
问题描述
如何搜索子字符串的最后一个位置?
解决方案
此示例显示如何借助 strOrig.lastIndexOf(Stringname) 方法确定字符串中子字符串的最后一个位置。
public class SearchlastString { public static void main(String[] args) { String strOrig = "Hello world ,Hello Reader"; int lastIndex = strOrig.lastIndexOf("Hello"); if(lastIndex == - 1){ System.out.println("Hello not found"); } else { System.out.println("Last occurrence of Hello is at index "+ lastIndex); } } }
结果
上述代码示例将产生以下结果。
Last occurrence of Hello is at index 13
示例
此另一个示例展示了如何借助 strOrig.lastIndexOf(Stringname) 方法确定字符串中子字符串的最后位置。
public class HelloWorld{ public static void main(String []args) { String t1 = "Tutorialspoint"; int index = t1.lastIndexOf("p"); System.out.println(index); } }
上述代码示例将产生以下结果。
9
java_strings.html