Java 程式查詢字串中某個字元


要查詢字串中的某個字元,請使用 indexOf() 方法

比如,下面是我們的字串。

String str = "testdemo";

找到字串中的字元“d”並獲取索引。

int index = str.indexOf( 'd');

示例

 線上演示

public class Demo {
   public static void main(String []args) {
      String str = "testdemo";
      System.out.println("String: "+str);
      int index = str.indexOf( 'd' );
      System.out.printf("'d' is at index %d, index);
   }
}

輸出

String: testdemo
'd' is at index 4

讓我們看另一個示例。如果找不到字元,該方法將返回 -1 −

示例

 線上演示

public class Demo {
   public static void main(String []args) {
      String str = "testdemo";
      System.out.println("String: "+str);
      int index = str.indexOf( 'h' );
      System.out.printf("'h' is at index %d, index);
   }
}

輸出

String: testdemo
'h' is at index -1

更新於:21-6-2024

14K+ 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.