如何在字符串中找到第n次出现的字符? [英] How to find nth occurrence of character in a string?
问题描述
类似于发布的问题 here,正在查找寻求 Java 中的解决方案.
即如何从一个字符串中找到一个字符/字符串第n次出现的索引?
示例:/folder1/folder2/folder3/".在这种情况下,如果我要求第三次出现斜杠 (/),它会出现在 folder3 之前,并且我希望返回这个索引位置.我的实际意图是从第 n 次出现的字符中将其子串起来.
Java API 中是否有任何方便/随时可用的方法,或者我们是否需要自己编写一个小逻辑来解决这个问题?
还有,
- 我在 Apache Commons Lang 的 StringUtils,但我没有找到.
- 正则表达式在这方面有帮助吗?
如果您的项目已经依赖于 Apache Commons,您可以使用 StringUtils.ordinalIndexOf
,否则,这是一个实现:
public static int ordinalIndexOf(String str, String substr, int n) {int pos = str.indexOf(substr);而 (--n > 0 && pos != -1)pos = str.indexOf(substr, pos + 1);返回位置;}
<小时>
这篇文章已被改写为文章这里.>
Similar to a question posted here, am looking for a solution in Java.
That is, how to find the index of nth occurrence of a character/string from a string?
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.
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?
Also,
- I quickly searched whether any method is supported for this purpose at Apache Commons Lang's StringUtils, but I don't find any.
- Can regular expressions help in this regard?
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;
}
This post has been rewritten as an article here.
这篇关于如何在字符串中找到第n次出现的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!