如何搜索指定子字符串的最后一次出现的位置?
此示例显示如何使用strOrig.lastIndexOf(Stringname)
方法确定指定子字符串在字符串内的最后出现位置。
package com.zaixian;
public class SearchlastString {
public static void main(String[] args) {
String strOrig = "Hello world ,Hello Reader,Hello Sukida";
int lastIndex = strOrig.lastIndexOf("Hello");
if (lastIndex == -1) {
System.out.println("Hello not found");
} else {
System.out.println("Last occurrence of Hello is at index "
+ lastIndex);
}
}
}
执行上示例代码,得到以下结果 -
Last occurrence of Hello is at index 26
示例
下面示例显示了如何使用strOrig.lastIndexOf(Stringname)
方法来确定指定子字符串在字符串中最后出现的位置。
package com.zaixian;
public class SearchlastString2 {
public static void main(String[] args) {
String t1 = "Welcome to xuhuhu.com";
int index = t1.lastIndexOf("o");
System.out.println("Found last index is: "+index);
}
}
执行上示例代码,得到以下结果 -
Found last index is: 19