Java 中lastIndexOf的用法

public class GetLastIndex {
public static void main(String[] args) {
String str = “mingri”; //定义字符串对象
int lastIndex = str.lastIndexOf(105,4);//查询字符i在指定范围内最后一次出现的索引位置
System.out.println(“i所在的索引位置为:”+lastIndex); //输出检索后结果
}
}

String str = “mingri”;
0 – m
1 – i
2 – n
3 – g
4 – r
5 – i
lastIndexOf是反向查找
str.lastIndexOf(105,4)这句的意思,是从索引为4的地方向前查找
所以输出是1

如果要找i最后一次出现的位置可以这样写:
int lastIndex = str.lastIndexOf(105, str.length());

猜你喜欢

转载自blog.csdn.net/m0_38017679/article/details/77192863