📜  Java字符串之-lastIndexOf()

📅  最后修改于: 2020-09-26 05:41:56             🧑  作者: Mango

Java字符串lastIndexOf()

Java 字符串 lastIndexOf()方法返回给定字符值或子字符串的最后一个索引。如果找不到,则返回-1。索引计数器从零开始。

内部实现

public int lastIndexOf(int ch) {
        return lastIndexOf(ch, value.length - 1);
    }

Signature(签名)

Java中有4种类型的lastIndexOf方法。 lastIndexOf方法的签名如下:

No. Method Description
1 int lastIndexOf(int ch) returns last index position for the given char value
2 int lastIndexOf(int ch, int fromIndex) returns last index position for the given char value and from index
3 int lastIndexOf(String substring) returns last index position for the given substring
4 int lastIndexOf(String substring, int fromIndex) returns last index position for the given substring and from index

参数

ch:char值,即单个字符,例如“ a”

fromIndex:从此处获取char值或子字符串的索引的索引位置

substring:要在此字符串搜索的子字符串

返回值或类型

字符串的最后一个索引

Java String lastIndexOf()方法示例

public class LastIndexOfExample{
public static void main(String args[]){
String s1=this is index of example;//there are 2 's' characters in this sentence
int index1=s1.lastIndexOf('s');//returns last index of 's' char value
System.out.println(index1);//6
}}

输出:

"6

Java字符串lastIndexOf(int ch,int fromIndex)方法示例

在这里,我们通过指定fromIndex从字符串中找到最后一个索引

public class LastIndexOfExample2 {
public static void main(String[] args) {
String str = This is index of example;
int index = str.lastIndexOf('s',5);
System.out.println(index);
}
}

输出:

3

Java String lastIndexOf(String substring)方法示例

它返回子字符串的最后一个索引。

public class LastIndexOfExample3 {
public static void main(String[] args) { 
String str = This is last index of example;
int index = str.lastIndexOf(of);
System.out.println(index);
}
}

输出:

19

Java字符串lastIndexOf(String substring,int fromIndex)方法示例

它从fromIndex返回子字符串的最后一个索引。

public class LastIndexOfExample4 {
public static void main(String[] args) { 
String str = This is last index of example;
int index = str.lastIndexOf(of, 25);
System.out.println(index);
index = str.lastIndexOf(of, 10);
System.out.println(index); // -1, if not found
}
}

输出:

19
-1