一、其方法主要有4个:
- lastIndexOf(int ch) ,返回指定字符在此字符串中最后一次出现处的索引。
- lastIndexOf(int ch , int fromIndex) ,返回指定字符在此字符串中最后一次出现处的索引,从指定的索引处开始进行反向搜索。
- lastIndexOf(String str),返回指定子字符串在此字符串中最右边出现处的索引。
- lastIndexOf(String str , int fromIndex),返回指定子字符串在此字符串中最后一次出现处的索引,从指定的索引开始反向搜索。
二、参数
- ch – 字符。
- fromIndex – 开始搜索的索引位置。
- str – 要搜索的子字符串。
三、返回值
- 指定子字符串在字符串中第一次出现处的索引值。
四、示例:
String str = "01234567890123456789";
//查找字符串“01234567890123456789”中字符‘8'所在的位置(索引从0开始,从前往后搜索)
System.out.println(str.lastIndexOf('8')); //18
//查找字符串“01234567890123456789”中字符‘8'所在的位置,从索引为9的位置,即“0123456789”,从后往前搜索。
System.out.println(str.lastIndexOf('8',9)); //8
//查找字符串“01234567890123456789”中字符串‘56'所在的位置(索引从0开始,从前往后搜索),返回的是“56”中“5”的位置。
System.out.println(str.lastIndexOf("56")); //15
//查找字符串“01234567890123456789”中字符‘8'所在的位置,从索引为9的位置,即“0123456789”,从后往前搜索,返回的是“56”中“5”的位置。
System.out.println(str.lastIndexOf("56",9)); //5
注意:System.out.println(str.lastIndexOf("56",5))
在这个例子中,按理说在 “012345” 中是查找不到 “56”,但返回的却不是 -1,而是 5。
经过测试,由于查找字符串时,只返回匹配到的字符串中第一个字符的下标。所以即使你将 fromIndex 的值设置了“5”,你匹配 “567890123456789” 也是能匹配到的,返回值也是 5。
类似例如:
String str1 = "Hello World!";
System.out.println(str1.lastIndexOf('o')); //7
System.out.println(str1.lastIndexOf("o ",4)); //4
System.out.println(str1.lastIndexOf("o World",4)); //4
• 由 ChiKong_Tam 写于 2020 年 9 月 17 日