用 Java 在字串中查詢字元的索引


使用 indexOf() 方法來查詢字串中字元的索引。

假設我們的字串如下。

String myStr = "amit";

現在,讓我們在上面的字串中查詢字元 't' 的索引。

strIndex = myStr.indexOf('t');

以下是最終示例。

示例

 即時演示

public class Demo {
    public static void main(String[] args) {
       String myStr = "amit";
       int strIndex = 0;
       System.out.println("String: "+myStr);
       // finding index of character t
       strIndex = myStr.indexOf('t');
       System.out.println("Character m found at index: "+strIndex);
    }
}

輸出

String: amit
Character m found at index: 3

更新時間:26-Jun-2020

1K+ 瀏覽

開啟您的事業

完成課程以獲得認證

開始使用
廣告
© . All rights reserved.