public class LastIndexOfExample {
public static void main(String[] args) {
String str = "Hello, hello, world!";
// 查找子字符串 "hello" 最后一次出现的位置,区分大小写
int index = str.lastIndexOf("hello");
System.out.println("最后一次出现 'hello' 的位置是: " + index); // 输出 7
// 如果要查找不区分大小写的 "hello"
String lowerCaseStr = str.toLowerCase();
int caseInsensitiveIndex = lowerCaseStr.lastIndexOf("hello");
System.out.println("最后一次出现 'hello' (不区分大小写) 的位置是: " + caseInsensitiveIndex); // 输出 7
// 查找子字符串 "world" 最后一次出现的位置
int worldIndex = str.lastIndexOf("world");
System.out.println("最后一次出现 'world' 的位置是: " + worldIndex); // 输出 14
// 如果查找的子字符串不存在
int notFoundIndex = str.lastIndexOf("java");
System.out.println("最后一次出现 'java' 的位置是: " + notFoundIndex); // 输出 -1
}
}
lastIndexOf
方法用于查找指定子字符串在字符串中最后一次出现的位置。它返回一个整数,表示子字符串的起始索引(从0开始),如果找不到则返回 -1
。lastIndexOf
方法来查找不同子字符串的位置,并且还展示了如何处理不区分大小写的情况。下一篇:java aes解密
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站