Java查找字符串中子串

int indexOf(int ch) 返回指定字符第一次出现的字符串内的索引。索引是从0开始,返回的是其对应的位置,注意:当找不到时返回-1;下同。

		String url = "https://blog.csdn.net/Butterfly_resting";
        int index= url.indexOf("/");
        System.out.println("index = " + index);
       //	index = 6  

int indexOf(int ch, int fromIndex) 返回指定字符第一次出现的字符串内的索引,以指定的索引开始搜索。

		//从第5位开始,匹配 字符c在url的位置
		String url = "https://blog.csdn.net/Butterfly_resting";
        int index = url.indexOf('c',4);
        System.out.println("index = " + index);

		//index = 13

int indexOf(String str) 返回指定子字符串第一次出现的字符串内的索引。

		//第一次出现Butterfly_resting的位置
		String url = "https://blog.csdn.net/Butterfly_resting";
		 int index = url.indexOf("Butterfly_resting");
        System.out.println("index = " + index);
		//index = 22

int indexOf(String str, int fromIndex) 返回指定子串的第一次出现的字符串中的索引,从指定的索引开始。

		//从第5位开始,匹配 字符串tt在url的位置
		String url = "https://blog.csdn.net/Butterfly_resting";
		int index = url.indexOf("tt",5);
        System.out.println("index = " + index);
		//index = 24

int lastIndexOf(int ch) 返回指定字符的最后一次出现的字符串中的索引。

	String url = "https://blog.csdn.net/Butterfly_resting";
	int lastIndex = url.lastIndexOf('/');
    System.out.println("lastIndex = " + lastIndex);
    //lastIndex = 21

int lastIndexOf(int ch, int fromIndex) 返回指定字符的最后一次出现的字符串中的索引,从指定的索引开始向后搜索。 【就是指定位置,然后在左字串中找】

	//
	String url = "https://blog.csdn.net/Butterfly_resting";
	int lastIndex = url.lastIndexOf("/",10);
    System.out.println("lastIndex = " + lastIndex);
    //lastIndex = 7

int lastIndexOf(String str) 返回指定子字符串最后一次出现的字符串中的索引。

	String url = "https://blog.csdn.net/Butterfly_resting";
	int lastIndex = url.lastIndexOf("tt");
    System.out.println("lastIndex = " + lastIndex);
    //lastIndex = 24

int lastIndexOf(String str, int fromIndex) 返回指定子字符串的最后一次出现的字符串中的索引,从指定索引开始向后搜索。

	//从第5位开始,在左边的字串找出字符串tt在url的位置
	String url = "https://blog.csdn.net/Butterfly_resting";
	int lastIndex = url.lastIndexOf("tt",5);
    System.out.println("lastIndex = " + lastIndex);
	//lastIndex = 1

上面位置匹配都可以与substring方法来截取字串。
String substring(int beginIndex)
返回一个字符串,该字符串是此字符串的子字符串。
String substring(int beginIndex, int endIndex)
返回一个字符串,该字符串是此字符串的子字符串。

示例:

		//截取url的参数部分
		String url = "/blog.csdn.net/Butterfly_resting?status=1";
        int index = url.indexOf('?');
        System.out.println(url.substring(index));
        //status=1
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值