原文: https://beginnersbook.com/2013/12/java-string-indexof-method-example/
Java String indexOf()方法用于查找给定String中指定字符或子字符串的索引。String类中有 4 种变体:
indexOf()方法签名
int indexOf(int ch):返回给定String中字符ch的第一次出现的索引。
int indexOf(int ch, int fromIndex):返回给定字符串中指定索引fromIndex后,字符ch的第一次出现的索引。例如,如果像str.indexOf('A', 20)那样调用indexOf()方法,那么它将开始在字符串str中索引 20 之后查找字符'A'。
int indexOf(String str):返回特定String中字符串str的索引。
int indexOf(String str, int fromIndex):返回给定字符串中指定索引fromIndex后,字符串str的索引。
如果在特定String中找不到指定的char/substring,则上述所有函数都返回 -1 。
Java String indexOf()方法示例
public class IndexOfExample{public static void main(String args[]) {String str1 = new String("This is a BeginnersBook tutorial");String str2 = new String("Beginners");String str3 = new String("Book");String str4 = new String("Books");System.out.println("Index of B in str1: "+str1.indexOf('B'));System.out.println("Index of B in str1 after 15th char:"+str1.indexOf('B', 15));System.out.println("Index of B in str1 after 30th char:"+str1.indexOf('B', 30));System.out.println("Index of string str2 in str1:"+str1.indexOf(str2));System.out.println("Index of str2 after 15th char"+str1.indexOf(str2, 15));System.out.println("Index of string str3:"+str1.indexOf(str3));System.out.println("Index of string str4"+str1.indexOf(str4));System.out.println("Index of hardcoded string:"+str1.indexOf("is"));System.out.println("Index of hardcoded string after 4th char:"+str1.indexOf("is", 4));}}
输出:
Index of B in str1: 10Index of B in str1 after 15th char:19Index of B in str1 after 30th char:-1Index of string str2 in str1:10Index of str2 after 15th char-1Index of string str3:19Index of string str4-1Index of hardcoded string:2Index of hardcoded string after 4th char:5
indexOf()方法的另一个例子
让我们举一个简短的例子,我们使用indexOf()方法找到给定字符和子字符串的索引。
public class JavaExample {public static void main(String[] args) {String str = "Java String";char ch = 'J';char ch2 = 'S';String subStr = "tri";int posOfJ = str.indexOf(ch);int posOfS = str.indexOf(ch2);int posOfSubstr = str.indexOf(subStr);System.out.println(posOfJ);System.out.println(posOfS);System.out.println(posOfSubstr);}}
输出:

