如何在字符串中找到第n个字符? [英] How to find nth occurrence of character in a string?

查看:226
本文介绍了如何在字符串中找到第n个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于发布的问题这里的字符,我正在寻找
的Java解决方案。

Similar to a question posted here, am looking for a solution in Java.

也就是说,如何找到第n个索引从字符串中出现字符/字符串?

That is, how to find the index of nth occurrence of a character/string from a string?

示例: / folder1 / folder2 / folder3 /
在这种情况下,如果我要求第3次出现斜杠(/),它会出现在folder3之前,我希望返回这个索引位置。我的实际意图是从第n次出现的字符中对其进行子串。

Example: "/folder1/folder2/folder3/". In this case, if I ask for 3rd occurrence of slash (/), it appears before folder3, and I expect to return this index position. My actual intention is to substring it from nth occurrence of a character.

Java API中是否有任何方便/现成的方法,或者我们是否需要编写我们自己的一个小逻辑来解决这个问题?

Is there any convenient/ready-to-use method available in Java API or do we need to write a small logic on our own to solve this?

此外,


  1. I在Apache Commons Lang的 StringUtils ,但我找不到。

  2. 正则表达式可以帮助这方面吗?

  1. I quickly searched whether any method is supported for this purpose at Apache Commons Lang's StringUtils, but I don't find any.
  2. Can regular expressions help in this regard?


推荐答案

如果您的项目已经依赖于Apache Commons,您可以使用 StringUtils.ordinalIndexOf ,否则,这是一个实现:

If your project already depends on Apache Commons you can use StringUtils.ordinalIndexOf, otherwise, here's an implementation:

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;
}






此帖子已被重写作为此处的文章。

这篇关于如何在字符串中找到第n个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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