在Java中查找字符串中第二次出现的子字符串 [英] Finding second occurrence of a substring in a string in Java

查看:4146
本文介绍了在Java中查找字符串中第二次出现的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个字符串,比如说,itiswhatitis和一个子字符串,比如说,
当字符串第二次出现时,我需要找到'i'的索引在原始字符串中。

We are given a string, say, "itiswhatitis" and a substring, say, "is". I need to find the index of 'i' when the string "is" occurs a second time in the original string.

String.indexOf(is)在这种情况下将返回2。我希望在这种情况下输出为10.

String.indexOf("is") will return 2 in this case. I want the output to be 10 in this case.

推荐答案

使用 indexOf() ,它将起始索引(fromIndex)作为第二个参数:

Use overloaded version of indexOf(), which takes the starting index (fromIndex) as 2nd parameter:

str.indexOf("is", str.indexOf("is") + 1);

这篇关于在Java中查找字符串中第二次出现的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆