16.6字符串的查找字符或字符串并返回索引

package study;
//查找字符串所要的字符并返回其索引(下标)
public class exercise {
	public static void main(String[] args) {
		String str="123456,123456";
		String str1="23";
//从开头开始查找,没找到为-1
//找到该字符在字符串中第一次出现的索引(下标)
		int a=str.indexOf('1');
		int b=str.indexOf('2');
		System.out.println(a);
		System.out.println(b);

		System.out.println("**********分割线*********");
		
//指定某位置后再开始查找该字符在字符串中第一次出现的索引(下标)
		int c=str.indexOf('1', 4);
		int d=str.indexOf('2', 5);
		System.out.println(c);
		System.out.println(d);

		System.out.println("**********分割线*********");
		
//该指定子字符串在原字符串第一次出现的索引(下标)
		int e=str.indexOf(str1);
		System.out.println(e);

		System.out.println("**********分割线*********");
		
//指定某位置后再开始查找该指定子字符串在原字符串第一次出现的索引(下标)
		int f=str.indexOf(str1, 4);
		System.out.println(f);

		System.out.println("**********分割线*********");
		

	}
}

package study;
//查找字符串所要的字符并返回其索引(下标)
public class exercises {
		public static void main(String[] args) {
			String str="123456,123456";
			String str1="23";
//从末尾开始查找,没找到为-1
//找到该字符在字符串中最后一次出现的索引(下标)
			int a=str.lastIndexOf('2');
			System.out.println(a);
			
			System.out.println("*********分割线*********");
			
//指定某位置后再开始查找该字符在字符串中最后一次出现的索引(下标)
			int b=str.lastIndexOf('3', 11);//(要寻找的字符,限定从最后的第几个开始寻找)
			System.out.println(b);
		
			System.out.println("*********分割线*********");
			
//该指定子字符串在原字符串最后一次出现的索引(下标)
			int c=str.lastIndexOf(str1);
			System.out.println(c);
			
			System.out.println("*********分割线*********");

//指定某位置后再开始查找该指定子字符串在原字符串最后一次出现的索引(下标)
			int d=str.lastIndexOf(str1, 5);
			System.out.println(d);
		}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值