查詢一組字元的最後一個索引的 Java 程式


使用 lastIndexOf() 方法來搜尋一組字元的最後一個索引。假設我們的字串如下。

String myStr = "pqrstuvwxyzpqrst";

在字串中搜索子字串“pqrs”以獲取其在字串中最後出現的位置。我們從索引 3 開始搜尋。

int begnIndex = 3;
strLastIndex = myStr.indexOf("pqrs", begnIndex);

以下是一個示例,其中我們正在搜尋子字串“pqrs”的最後一個索引

示例

 即時演示

public class Demo {
    public static void main(String[] args) {
       String myStr = "pqrstuvwxyzpqrst";
       int strLastIndex = 0;
       System.out.println("String: "+myStr);
       strLastIndex = myStr.lastIndexOf("pqrs");
       System.out.println("The last index of substring pqrs in the string "+myStr+" = "+strLastIndex);
    }
}

輸出

String: pqrstuvwxyzpqrst
The last index of substring pqrs in the string pqrstuvwxyzpqrst = 11

更新於: 2020 年 6 月 26 日

147 次瀏覽

開啟你的職業

透過完成課程獲得認證

開始
廣告