参考:Java indexOf() 方法
indexOf() 方法有以下四种形式:
public int indexOf(int ch): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
public int indexOf(int ch, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
int indexOf(String str): 返回指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -1。
int indexOf(String str, int fromIndex): 返回从 fromIndex 位置开始查找指定字符在字符串中第一次出现处的索引,如果此字符串中没有这样的字符,则返回 -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 第一次出现的位置 :" );
System.out.println(Str.indexOf( 'i' ));
System.out.print("从第10个位置查找字符 s 第一次出现的位置 :" );
System.out.println(Str.indexOf( 's', 10 ));
System.out.print("子字符串 SubStr1 第一次出现的位置:" );
System.out.println( Str.indexOf( SubStr1 ));
System.out.print("从第十五个位置开始搜索子字符串 SubStr1 第一次出现的位置 :" );
System.out.println( Str.indexOf( SubStr1, 11 ));
System.out.print("子字符串 SubStr2 第一次出现的位置 :" );
System.out.println(Str.indexOf( SubStr2 ));
}
}
运行结果如下:
image.png