我正在尝试创建一个函数,该函数返回给定字符在字符串中第 N 次出现的索引。
这是我的尝试:
private int IndexOfNth(string str, char c, int n)
{
int index = str.IndexOf(c) + 1;
if (index >= 0)
{
string temp = str.Substring(index, str.Length - index);
for (int j = 1; j < n; j++)
{
index = temp.IndexOf(c) + 1;
if (index < 0)
{
return -1;
}
temp = temp.Substring(index, temp.Length - index);
}
index = index + (str.Length);
}
return index;
}
这应该找到第一个出现的地方,砍掉字符串的前面部分,从新的子串中找到第一个出现的地方,一直到找到第 n 个出现的索引。但是我没有考虑最终子字符串的索引将如何从原始字符串中的原始实际索引偏移。我该如何进行这项工作?
还有一个附带问题,如果我希望 char 成为制表符,我应该传递这个函数 '\t' 还是什么?
最佳答案
不要那样做; IndexOf
采用第二个参数,指定从哪里开始。
private static int IndexOfNth(string str, char c, int n) {
int s = -1;
for (int i = 0; i < n; i++) {
s = str.IndexOf(c, s + 1);
if (s == -1) break;
}
return s;
}
关于c# - 获取字符串中字符第 n 次出现的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11363083/