共計 607 個字符,預計需要花費 2 分鐘才能閱讀完成。
在 Java 中,indexOf
方法用于查找指定字符或子字符串在字符串中第一次出現的位置。它有兩種形式的使用:
- 查找指定字符的位置:
String str = "Hello, world!";
int index = str.indexOf('o');
System.out.println(index); // 輸出 4
- 查找指定子字符串的位置:
String str = "Hello, world!";
int index = str.indexOf("world");
System.out.println(index); // 輸出 7
如果要查找從指定位置開始的第一次出現的位置,可以使用帶有第二個參數的 indexOf
方法:
String str = "Hello, world!";
int index = str.indexOf('o', 5); // 從索引為 5 的位置開始查找
System.out.println(index); // 輸出 7
如果要查找最后一次出現的位置,可以使用 lastIndexOf
方法:
String str = "Hello, world!";
int index = str.lastIndexOf('o');
System.out.println(index); // 輸出 8
需要注意的是,indexOf
方法返回的是字符或子字符串第一次出現的索引,如果找不到指定字符或子字符串,返回 -1。
丸趣 TV 網 – 提供最優質的資源集合!
正文完