例如:
在字符串中搜索“cjavapy”的首次出现:String myStr = "c java python is cjavapy and www.cjavapy.com";
System.out.println(myStr.indexOf("cjavapy"));
1、定义和用法
indexOf()方法返回字符串中首次出现的指定字符的索引位置。
提示:使用lastIndexOf方法返回字符串中最后一次出现指定字符的位置。
2、调用语法
有4个indexOf()方法:public int indexOf(String str)
public int indexOf(String str, int fromIndex)
public int indexOf(int char)
public int indexOf(int char, int fromIndex)
3、参数说明参数描述
strString值,表示要搜索的字符串
fromIndexint值,表示从中开始搜索的索引位置
charint值,表示单个字符,例如,'A'或Unicode值
4、方法说明返回值:int值,表示字符串中字符首次出现的索引,如果从未出现,则为-1
5、使用示例
例如:
在字符串中找到字母"java"的第一个匹配项,从位置10开始搜索:public class Main {
public static void main(String[] args) {
String myStr = "c java python is cjavapy and www.cjavapy.com";
System.out.println(myStr.indexOf("java", 10));
}
}