參考:Java indexOf() 方法
indexOf() 方法有以下四種形式:
public int indexOf(int ch): 返回指定字符在字符串中第一次出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
public int indexOf(int ch, int fromIndex): 返回從 fromIndex 位置開始查找指定字符在字符串中第一次出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
int indexOf(String str): 返回指定字符在字符串中第一次出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
int indexOf(String str, int fromIndex): 返回從 fromIndex 位置開始查找指定字符在字符串中第一次出現(xiàn)處的索引,如果此字符串中沒有這樣的字符,則返回 -1。
測試代碼如下:
public class Test {
public static void main(String[] args) {
String Str = new String("hello,this is a test");
String SubStr1 = new String("is");
String SubStr2 = new String("test");
System.out.print("查找字符i 第一次出現(xiàn)的位置 :" );
System.out.println(Str.indexOf( 'i' ));
System.out.print("從第10個位置查找字符 s 第一次出現(xiàn)的位置 :" );
System.out.println(Str.indexOf( 's', 10 ));
System.out.print("子字符串 SubStr1 第一次出現(xiàn)的位置:" );
System.out.println( Str.indexOf( SubStr1 ));
System.out.print("從第十五個位置開始搜索子字符串 SubStr1 第一次出現(xiàn)的位置 :" );
System.out.println( Str.indexOf( SubStr1, 11 ));
System.out.print("子字符串 SubStr2 第一次出現(xiàn)的位置 :" );
System.out.println(Str.indexOf( SubStr2 ));
}
}
運行結(jié)果如下:

image.png