个性化阅读
专注于IT技术分析

Java字符串lastIndexOf()

点击下载

本文概述

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


内部实施

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

签名

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

没有。 方法 描述
1 int lastIndexOf(int ch) 返回给定char值的最后一个索引位置
2 int lastIndexOf(int ch, int fromIndex) 返回给定char值和索引的最后索引位置
3 int lastIndexOf(String substring) 返回给定子字符串的最后一个索引位置
4 int lastIndexOf(String substring, int fromIndex) 返回给定子字符串和索引的最后索引位置

参量

ch:char值, 即单个字符, 例如’一种’

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 String 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
赞(0)
未经允许不得转载:srcmini » Java字符串lastIndexOf()

评论 抢沙发

评论前必须登录!