1. lastIndexOf(String/int arg0, int arg1)
在当前字符串中小于arg1的范围中,查找指定字符串或字符。返回值同样为子串在原串中最后一次出现的相对位置,只不过查找有范围限制,超出范围的部分即便仍有子串,也无法找到。
- String s = "abcdefgabcdefg";
- int i = s.lastIndexOf("cd",8);
- System.out.println(i);
运行结果为:
- 2
注意与上一个例子做比较。
但是当范围当中包含了子串的前面的某一位或某几位时:
- String s = "abcdefgabcdefg";
- int i = s.lastIndexOf("cd",9);
- System.out.println(i);
运行结果为:
- 9
原因很简单,字符串比较时约束的范围仅限制住了首地址而没有约束长度。
2. indexOf(String/int arg0)
返回值为源字符串中子串最先出现的位置(参数int arg0同样指字符的ascii码值),若找不到,则返回-1。
indexOf的限制arg1参数限定的是由此位起始搜索,lastIndexOf限定的是搜索到此位为止。
- String s = "abcdefgabcdefg";
- int i = s.indexOf("cd",8);
- System.out.println(i);
运行结果为:
- 9
3.实例
lastIndexOf:
以上代码实例输出结果为:
Runoob 字符串最后出现的位置: 19
indexOf:
public class SearchStringEmp {
public static void main(String[] args) {
String strOrig = "Google Runoob Taobao";
int intIndex = strOrig.indexOf("Runoob");
if(intIndex == - 1){
System.out.println("没有找到字符串 Runoob");
}else{
System.out.println("Runoob 字符串位置 " + intIndex);
}
}}
以上代码实例输出结果为:
Runoob 字符串位置 7