c# - 获取字符串中字符第 n 次出现的索引

标签 c# .net string

我正在尝试创建一个函数,该函数返回给定字符在字符串中第 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/

相关文章:

c# - 使用 Repeater 和 SQL 自定义分页

c# - 通过 Azure Devops 部署 Nuget 包时未添加依赖项

java - 在 string.xml 中将占位符与 % 符号一起用于 String.format()

Xcode 中的 C++ 字符串

c# - 如何设置以编程方式创建的 xlsx 文件中单元格的宽度?

c# - 使用 LINQ 或 C# 清理字符串中特定 HTML 的算法

c# - 安装 OpenXML 文件转换器

.net - 使用 PowerShell 从文件夹中获取文件名的最快\最佳方法是什么?

c# - Crystal 报表 : Operation not yet implemented

c++ - 将 `char []` 传递给接受 `std::string&` 的函数是好习惯吗