Java 程式,用於從指定索引處搜尋子串


使用 indexOf() 方法從給定位置搜尋子串。

假設以下內容為我們的字串。

String myStr = " pqrstuvwxyzpqrst";

在字串中搜索子串“pqrs”。我們從索引 3 開始搜尋。

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

示例

 線上演示

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

輸出

String: pqrstuvwxyzpqrst
The index of substring pqrs in the string beginning from index 3 = 11

更新於:26-6-2020

338 次瀏覽

開始你的 職業

完成課程並獲得認證

開始
廣告
© . All rights reserved.