String的indexOf和lastIndexOf

1.indexOf (String str) 从字符串开始(索引为0)位置,寻找相应的子字符串,返回第一次出现的索引位置。否则返回-1,

方向从左往右找。

2.indexOf(String str, int fromIndex) 从指定索引开始(包括指定位置),寻找相应的子字符串,返回第一次出现的索引位置。

否则返回-1,方向从左往右找。

3.lastIndexOf (String str)从字符串末尾(索引为字符串长度-1)位置,寻找相应的子字符串,返回最后一次出现的索引位置。

否则返回-1,方向从右向左。

4.lastIndexOf (String str,int  fromIndex)从字符串指定位置,寻找相应的子字符串,返回最后一次出现的索引位置。

否则返回-1,方向从右向左。

注:lastIndexOf(String str ,int  fromIndex)容易出错,可以理解为0-fromIndex(包括该位置)这段字符串中,最后一次出现子字符串的位置。

package com;



public class test {
	public static void main(String[] args)  {
		String  str="123456789123456789";
		int posLast=str.lastIndexOf("1"); //9
		int posLast1=str.lastIndexOf("1",11);//9
		int posLast2=str.lastIndexOf("1",8);//0
		int pos=str.indexOf("1");//0
		int pos1=str.lastIndexOf("1",0);//0
		int pos2=str.lastIndexOf("1",9);//9
		System.out.println("last**************");
		System.out.println(posLast);
		System.out.println(posLast1);
		System.out.println(posLast2);
		System.out.println("first*************");
		System.out.println(pos);
		System.out.println(pos1);
		System.out.println(pos2);
		
	}

}

 

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值