除非我遗漏了一个明显的内置方法,否则获取字符串中字符串的_n_th匹配项的最快方法是什么?
我意识到我可以通过在循环的每次迭代中更新IndexOf方法的开始索引来循环该方法。但这样做对我来说似乎是浪费。
发布于 2008-10-09 10:26:51
这基本上就是你需要做的--或者至少,这是最简单的解决方案。你所“浪费”的就是n次方法调用的开销--如果你仔细想想,你实际上不会检查任何情况两次。(IndexOf将在找到匹配项后立即返回,您将继续从它停止的位置继续。)
发布于 2009-10-07 04:39:45
private int IndexOfOccurence(string s, string match, int occurence)
{
int i = 1;
int index = 0;
while (i <= occurence && (index = s.IndexOf(match, index + 1)) != -1)
{
if (i == occurence)
return index;
i++;
}
return -1;
}
或者在带有扩展方法的C#中
public static int IndexOfOccurence(this string s, string match, int occurence)
{
int i = 1;
int index = 0;
while (i <= occurence && (index = s.IndexOf(match, index + 1)) != -1)
{
if (i == occurence)
return index;
i++;
}
return -1;
}
发布于 2018-08-09 03:58:15
经过一些基准测试后,这似乎是最简单、最有效的解决方案
public static int IndexOfNthSB(string input,
char value, int startIndex, int nth)
{
if (nth < 1)
throw new NotSupportedException("Param 'nth' must be greater than 0!");
var nResult = 0;
for (int i = startIndex; i < input.Length; i++)
{
if (input[i] == value)
nResult++;
if (nResult == nth)
return i;
}
return -1;
}
https://stackoverflow.com/questions/186653
复制相似问题