從給定位置搜尋 Java 中的字元


使用 indexOf() 方法從給定位置搜尋字元。

假設以下字串。

String myStr = "Amit Diwan";

在此,我們在字串中搜索字元“i”。我們將從 4 開始索引進行搜尋。

int begnIndex = 4;
System.out.println("String: "+myStr);
strLastIndex = myStr.indexOf('i', begnIndex);

以下為完整示例。

示例

 線上演示

public class Demo {
   public static void main(String[] args) {
      String myStr = "Amit Diwan";
      int strLastIndex = 0;
      int begnIndex = 4;
      System.out.println("String: "+myStr);
      strLastIndex = myStr.indexOf('i', begnIndex);
      System.out.println("The index of character a in the string beginning from index "+begnIndex+" ="+strLastIndex);
   }
}

輸出

String: Amit Diwan
The index of character a in the string beginning from index 4 = 6

更新於: 26-Jun-2020

112 次瀏覽

開啟職業生涯

完成課程即可獲得認證

開始吧
廣告
© . All rights reserved.