如何搜索 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.htm
广告
© . All rights reserved.