除非我遗漏了一个明显的内置方法,否则获取字符串中第 n 次出现的最快方法是什么?
我意识到我可以循环 IndexOf方法通过在循环的每次迭代中更新其起始索引。但这样做对我来说似乎很浪费。
最佳答案
您确实可以使用正则表达式 /((s).*?){n}/
来搜索第 n 次出现的子字符串 s
。
在 C# 中它可能看起来像这样:
public static class StringExtender
{
public static int NthIndexOf(this string target, string value, int n)
{
Match m = Regex.Match(target, "((" + Regex.Escape(value) + ").*?){" + n + "}");
if (m.Success)
return m.Groups[2].Captures[n - 1].Index;
else
return -1;
}
}
注意:我在原来的解决方案中添加了Regex.Escape
,以允许搜索对正则表达式引擎有特殊意义的字符。
关于c# - 获取字符串第 n 次出现的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/186653/