lastIndexOf Java中
lastIndexOf是Java中的一个字符串方法,它用于查找指定字符串在当前字符串中最后一次出现的位置。该方法有两种重载形式:
public int lastIndexOf(int ch): 查找指定字符在当前字符串中最后一次出现的位置,返回索引值(从0开始),如果未找到则返回-1。
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
Java lastIndexOf
方法的使用
String 类中的 lastIndexOf
在 Java 中,String
类提供了多个重载版本的 lastIndexOf
方法来查找指定字符或子字符串最后一次出现的位置。
- 按单个字符查找
此方法返回指定字符在此字符串中最后出现处的索引。如果未找到该字符,则返回 -1
。
public int lastIndexOf(int ch)
示例:
String str = "hello world";
int index = str.lastIndexOf('o');
System.out.println(index); // Output 7
- 按子串查找
此方法返回指定子字符串在此字符串中最右边出现处的索引; 如果未找到该子字符串,则返回 -1
。
public int lastIndexOf(String str)
示例:
String sentence = "Java is fun, Java programming is easy.";
int lastIndex = sentence.lastIndexOf("Java");
System.out.println(lastIndex); // Output 20
- 带起始位置参数的方法变体
这些方法允许从特定位置向前搜索给定字符或子串。
public int lastIndexOf(int ch, int fromIndex)
public int lastIndexOf(String str, int fromIndex)
示例:
String text = "abracadabra";
// 查找 'a' 的最后一个实例,但在索引8之前停止搜索
int pos = text.lastIndexOf('a', 8);
System.out.println(pos); // Output 6
java中lastIndexOf用法
在Java中,indexOf()
和 lastIndexOf()
是字符串类(String)提供的两个常用方法,用于查找指定字符、子串在字符串中的位置。
indexOf(String str)
:这个方法返回指定子串str
第一次出现的位置(从0开始计数)。如果找不到该子串,则返回-1。String s = "Hello World"; int index = s.indexOf("World"); // 返回6,因为"World"从索引6开始
lastIndexOf(String str)
:这个方法与indexOf()
类似,但它会寻找子串str
在字符串中最后一次出现的位置。同样,如果没有找到,它将返回-1。int lastIndex = s.lastIndexOf("o"); // 返回8,因为最后一个字母'o'的索引是8(注意:"o"在"World"和"lo"中都出现了)
如果你需要在特定范围内查找子串,可以先获取子字符串,然后应用indexOf()
或 lastIndexOf()
:
int start = 7; // 要搜索的起始位置
String substring = s.substring(start);
int position = substring.lastIndexOf("World");
相关推荐

















