indexOf的四种用法:
-
int indexOf(int ch) 返回指定字符在此字符串中第一次出现处的索引。
-
int indexOf(int ch, int fromIndex) 返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
-
int indexOf(String str) 返回指定子字符串在此字符串中第一次出现处的索引。
-
int indexOf(String str, int fromIndex) 返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
注:索引为ASCII码值
测试:
public class Test3 {
public static void main(String[] args) {
String str = "abcdefgh";
System.out.println("原字符串:");
System.out.println(str);
System.out.println("执行indexOf(int ch):");
System.out.println(str.indexOf(104));
System.out.println("执行indexOf(String str):");
System.out.println(str.indexOf("c"));
System.out.println("执行indexOf(int ch,int fromIndex):");
System.out.println(str.indexOf(101, 4));
System.out.println("执行indexOf(String str,int fromIndex):");
System.out.println(str.indexOf("cde", 0));
}
}