English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
String indexOf()方法返回字符串中指定字符/子字符串首次出现的索引。
String indexOf()方法的语法
string.indexOf(int ch, int fromIndex)
或
string.indexOf(string str, int fromIndex)
为了找到字符的索引,indexOf()使用以下两个参数:
ch - 要找到起始索引的字符
fromIndex(可选)- 如果传递了fromIndex,则从该索引开始搜索ch字符
要在字符串中找到指定子字符串的索引,indexOf()使用以下两个参数:
str - 要查找其起始索引的字符串
fromIndex(可选)- 如果传递了fromIndex,则从该索引开始搜索str字符串
返回指定字符/字符串的第一个匹配项的索引
如果找不到指定的字符/字符串,则返回 -1。
//Java字符串indexOf()只有一个参数 class Main { public static void main(String[] args) { String str1 = "Learn Java"; int result; //获取字符“ J”的索引 result = str1.indexOf('J'); System.out.println(result); // 6 //返回第一个出现的“a” result = str1.indexOf('a'); System.out.println(result); // 2 //字符不在字符串中 result = str1.indexOf('j'); System.out.println(result); // -1 //获取“ ava”的索引 result = str1.indexOf("ava"); System.out.println(result); // 7 //子字符串不在字符串中 result = str1.indexOf("java"); System.out.println(result); // -1 //字符串中空字符串的索引 result = str1.indexOf(""); System.out.println(result); // 0 } }
Note:
字符“ a”在“ Learn Java”字符串中多次出现。 indexOf()方法返回第一次出现的“ a”(即2)的索引。
如果传递空字符串,indexOf()返回0(在第一个位置找到)。这是因为空字符串是每个子字符串的子集。
class Main { public static void main(String[] args) { String str1 = "Learn Java programming"; int result; //Get the index of character 'a' //The search starts from index4start result = str1.indexOf('a', 4); System.out.println(result); // 7 //Get the index of 'Java' //The search starts from index8start result = str1.indexOf("Java", 8); System.out.println(result); // -1 } }
Note:
The first occurrence of 'a' in the 'Learn Java programming' string is at index2at.1Return the index of the second 'a'. Use indexOf('a', 4). This is because the search starts from index4starts.
The 'Java' string is located in the 'Learn Java programming' string. But, str1.indexOf("Java",8) returned-1(String not found). This is because the search starts from index8Start, and there is no 'Java' in 'va programming'.
Related Reading: Java String lastIndexOf()