如何搜尋 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.