在Java中,String.indexOf() 方法用于返回指定字符串在原字符串中第一次出现的位置索引。它有两种重载形式:
indexOf(int ch):返回指定字符在字符串中第一次出现的位置索引(从左到右搜索),如果未找到则返回 -1。indexOf(String str):返回指定字符串在字符串中第一次出现的位置索引(从左到右搜索),如果未找到则返回 -1。以下是使用示例:
String str = "Hello, World!";int index1 = str.indexOf('e'); // 返回值为 1int index2 = str.indexOf("World"); // 返回值为 7int index3 = str.indexOf('x'); // 返回值为 -1(未找到)int index4 = str.indexOf("ll", 3); // 从索引为 3 的位置开始搜索,返回值为 3System.out.println(index1);System.out.println(index2);System.out.println(index3);System.out.println(index4);输出结果为:
17-13 
