3 回答
TA贡献1770条经验 获得超3个赞
如果您的项目已经依赖于Apache Commons StringUtils.ordinalIndexOf,则可以使用,否则,这里是一个实现:
public static int ordinalIndexOf(String str, String substr, int n) {
int pos = str.indexOf(substr);
while (--n > 0 && pos != -1)
pos = str.indexOf(substr, pos + 1);
return pos;
}
TA贡献1872条经验 获得超4个赞
我认为查找字符串的第N个最简单的解决方案是使用来自Apache Commons的StringUtils.ordinalIndexOf()。
例:
StringUtils.ordinalIndexOf("aabaabaa", "b", 2) == 5
TA贡献1831条经验 获得超4个赞
发生两个简单的选择:
charAt()反复使用
indexOf()反复使用
例如:
public static int nthIndexOf(String text, char needle, int n)
{
for (int i = 0; i < text.length(); i++)
{
if (text.charAt(i) == needle)
{
n--;
if (n == 0)
{
return i;
}
}
}
return -1;
}
这可能不如indexOf重复使用好,但正确起来可能更简单。
添加回答
举报
