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() 参数
要查找字符的索引,
ch-要找到其起始索引的字符
fromIndex(可选)-如果 indexOf()
需要这两个参数:
fromIndex
被传递,则从这个索引开始搜索 ch
字符
要在字符串中查找指定子字符串的索引,
str-要找到其起始索引的字符串
fromIndex(可选)-如果 indexOf()
需要以下两个参数:
fromIndex
被传递,则从这个索引开始搜索 str
字符串
indexOf() 返回值
返回指定字符/字符串第一次出现的索引 如果未找到指定的字符/字符串,则返回-1。示例 1: Java 字符串 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: indexOf() 与 fromIndex 参数
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 } }
注意事项:
"Learn Java Programming"
字符串中第一次出现 'a'
的位置是索引 2、但是,第二个 'a'
<的索引 code>
在使用
str1.indexOf('a', 4)
时返回。这是因为搜索从索引 4 开始。
的索引>
"Java"
字符串位于 "Learn Java Programming"
字符串中。但是, str1.indexOf("Java", 8)
返回-1(未找到字符串)。这是因为搜索从索引 8 开始,并且 "va programming"
中没有 "Java"
。
推荐阅读: Java String lastIndexOf()