lastIndexOf Java中
时间: 2023-10-12 09:20:32 浏览: 57
lastIndexOf是Java中的一个字符串方法,它用于查找指定字符串在当前字符串中最后一次出现的位置。该方法有两种重载形式:
1. public int lastIndexOf(int ch): 查找指定字符在当前字符串中最后一次出现的位置,返回索引值(从0开始),如果未找到则返回-1。
2. public int lastIndexOf(String str): 查找指定字符串在当前字符串中最后一次出现的位置,返回索引值(从0开始),如果未找到则返回-1。
例如,以下代码将返回字符串"Hello World"中字符"o"和子字符串"or"最后一次出现的位置:
```
String str = "Hello World";
int index1 = str.lastIndexOf('o');
int index2 = str.lastIndexOf("or");
System.out.println(index1); // 输出7
System.out.println(index2); // 输出8
```
相关问题
java中lastindexof的用法
lastIndexOf是Java中的一个字符串方法,用于查找指定字符串在另一个字符串中最后一次出现的位置。
例如,如果我们有一个字符串"hello world",我们可以使用lastIndexOf方法来查找字符串"o"在该字符串中最后一次出现的位置。代码如下:
String str = "hello world";
int lastIndex = str.lastIndexOf("o");
System.out.println(lastIndex);
输出结果为:7
这意味着字符串"o"在字符串"hello world"中最后一次出现的位置是第8个字符(从开始计数)。如果指定的字符串没有在原字符串中出现,则返回-1。
java lastindexof方法
Java中的lastIndexOf方法是在字符串中查找最后一次出现指定字符或字符串的位置。语法如下:
int lastIndexOf(int ch)
int lastIndexOf(int ch, int fromIndex)
int lastIndexOf(String str)
int lastIndexOf(String str, int fromIndex)
其中第一个参数是要查找的字符或字符串,第二个参数(可选)是查找的起始位置。如果查找到,则返回最后一次出现该字符或字符串的位置,否则返回-1。
例如:
String str = "Hello World";
int index = str.lastIndexOf("l");
//index = 9
str = "Hello World";
index = str.lastIndexOf("l", 5);
//index = 3