java string.lastindexof,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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值