例如:
查找字符串中最后一次出现的“java”:String myStr = "c java python is cjavapy and www.cjavapy.com";
System.out.println(myStr.lastIndexOf("java"));
1、定义和用法
lastIndexOf()方法返回字符串中最后一次出现的指定字符的索引位置。
提示:使用indexOf()方法可返回字符串中首次出现的指定字符的索引位置。
2、调用语法
有4个lastIndexOf()方法:public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)
public int lastIndexOf(int char)
public int lastIndexOf(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.lastIndexOf("java", 10));
}
}