共計 1105 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中,indexOf()方法用于查找指定字符或字符串在字符串中第一次出現的位置。它的語法如下:
public int indexOf(int ch)
public int indexOf(int ch, int fromIndex)
public int indexOf(String str)
public int indexOf(String str, int fromIndex)
- 第一個重載方法
indexOf(int ch)
接受一個字符作為參數,并返回該字符在字符串中第一次出現的位置。如果字符不存在于字符串中,則返回 -1。
String str = "Hello World";
int index = str.indexOf('o');
System.out.println(index); // 輸出:4
- 第二個重載方法
indexOf(int ch, int fromIndex)
接受兩個參數,第一個參數是要查找的字符,第二個參數是搜索的起始位置。它從起始位置向后搜索字符串,并返回字符第一次出現的位置。如果字符不存在于指定的起始位置后的子字符串中,則返回 -1。
String str = "Hello World";
int index = str.indexOf('o', 5);
System.out.println(index); // 輸出:7
- 第三個重載方法
indexOf(String str)
接受一個字符串作為參數,并返回該字符串在原字符串中第一次出現的位置。如果字符串不存在于原字符串中,則返回 -1。
String str = "Hello World";
int index = str.indexOf("World");
System.out.println(index); // 輸出:6
- 第四個重載方法
indexOf(String str, int fromIndex)
接受兩個參數,第一個參數是要查找的字符串,第二個參數是搜索的起始位置。它從起始位置向后搜索字符串,并返回字符串第一次出現的位置。如果字符串不存在于指定的起始位置后的子字符串中,則返回 -1。
String str = "Hello World";
int index = str.indexOf("World", 4);
System.out.println(index); // 輸出:-1
請注意,indexOf()方法返回的是找到的字符或字符串的索引值,索引從 0 開始。如果要查找字符或字符串最后一次出現的位置,可以使用 lastIndexOf()方法。
String str = "Hello World";
int index = str.lastIndexOf('o');
System.out.println(index); // 輸出:7
丸趣 TV 網 – 提供最優質的資源集合!
正文完