indexOf()
方法返回指定字符/子字符串在 字符串 中首次出现的索引。
示例
class Main {
public static void main(String[] args) {
String str1 = "Java is fun";
int result;
// getting index of character 's'
result = str1.indexOf('s');
System.out.println(result);
}
}
// Output: 6
indexOf() 语法
String indexOf()
方法的语法要么是
string.indexOf(int ch, int fromIndex)
或者
string.indexOf(String str, int fromIndex)
这里,string是String
类的一个对象。
indexOf() 参数
要查找字符的索引,indexOf()
接受这两个参数
- ch - 要查找其起始索引的字符
- fromIndex (可选) - 如果传递了
fromIndex
,则从该索引开始搜索ch
字符
要查找字符串中指定子字符串的索引,indexOf()
接受这两个参数
- str - 要查找其起始索引的字符串
- fromIndex (可选) - 如果传递了
fromIndex
,则从该索引开始搜索str
字符串
indexOf() 返回值
- 返回指定字符/字符串首次出现的索引
- 如果找不到指定的字符/字符串,则返回 -1。
示例 1:Java String indexOf()
// Java String indexOf() with only one parameter
class Main {
public static void main(String[] args) {
String str1 = "Learn Java";
int result;
// getting index of character 'J'
result = str1.indexOf('J');
System.out.println(result); // 6
// the first occurrence of 'a' is returned
result = str1.indexOf('a');
System.out.println(result); // 2
// character not in the string
result = str1.indexOf('j');
System.out.println(result); // -1
// getting the index of "ava"
result = str1.indexOf("ava");
System.out.println(result); // 7
// substring not in the string
result = str1.indexOf("java");
System.out.println(result); // -1
// index of empty string in the string
result = str1.indexOf("");
System.out.println(result); // 0
}
}
注意事项
- 字符
'a'
在"Learn Java"
字符串中出现多次。indexOf()
方法返回'a'
第一次出现的索引(即 2)。 - 如果传递空字符串,
indexOf()
返回 0(在第一个位置找到。这是因为空字符串是每个子字符串的子集。
示例 2:带 fromIndex 参数的 indexOf()
class Main {
public static void main(String[] args) {
String str1 = "Learn Java programming";
int result;
// getting the index of character 'a'
// search starts at index 4
result = str1.indexOf('a', 4);
System.out.println(result); // 7
// getting the index of "Java"
// search starts at index 8
result = str1.indexOf("Java", 8);
System.out.println(result); // -1
}
}
注意事项
- 字符
'a'
在"Learn Java programming"
字符串中的第一个出现是在索引 2。但是,当使用str1.indexOf('a', 4)
时,会返回第二个'a'
的索引。这是因为搜索从索引 4 开始。 "Java"
字符串存在于"Learn Java programming"
字符串中。但是,str1.indexOf("Java", 8)
返回 -1(未找到字符串)。这是因为搜索从索引 8 开始,并且在"va programming"
中没有"Java"
。
另请阅读