Java lastIndexOf()方法
lastIndexOf()方法
Java中String类方法lastIndexOf()用于获取参数指定的字符或子串字符串中最后一次出现的索引(如果是子串的话,则是子串第一个字符在字符串中的索引位置),如果在调用对象的字符串(或在指定索引范围内)中并不存在该字符或子串,则该方法返回-1。lastIndexOf()语法如下:
public int lastIndexOf(int ch, int fromIndex)
或
public int lastIndexOf(String str, int fromIndex)
lastIndexOf()参数
参数 | 描述 |
---|---|
ch | 字符 |
fromIndex | 可选参数,int类型,为匹配查找的起始索引位置。 |
str | 字符串,即子串 |
重点提示:lastIndexOf()匹配查找字符或子串应该是采用倒序的形式,即,从最后一个索引位置为起始位置,然后从右往左匹配查找,具体的可参考下方实例代码中ind2和ind3的值。
lastIndexOf()返回值
int类型,如果匹配到参数指定的字符或子串,则返回该字符或子串在字符串对象中的索引,如果没有出现,则返回-1。
lastIndexOf()实例代码
注意思考,ind2为何匹配不到子串,而ind3则可以:
public class test {
public static void main(String[] args) {
String str = new String("微信公众号,全栈开发助手");
String sub_str = "全栈";
char ch = 'a';
int ind1 = str.lastIndexOf(sub_str);
int ind2 = str.lastIndexOf(sub_str,0);
int ind3 = str.lastIndexOf(sub_str, 9);
int i1 = str.lastIndexOf(ch);
System.out.println("ind1="+ind1+"; ind2="+ind2+" ind3="+ind3+" i1="+i1);
}
}
代码运行后,得到输出值为:
ind1=6; ind2=-1 ind3=6 i1=-1
免责声明:内容仅供参考,不保证正确性。