获取字符串第N次出现的索引

查找一个字符串出现的第一次可以用IndexOf,最后一次可以用LastIndexOf,若是想直接查第二次或第三次......,可以自己封装方法。

方法一:普通循环for,可读性高

    /// <summary>
    /// 获取字符串第n次出现的索引
    /// </summary>
    /// <param name="sourceStr">原始字符串</param>
    /// <param name="value">所要查询的字符串</param>
    /// <param name="n">第几次出现</param>
    /// <returns></returns>
    public static int IndexOfNth(string sourceStr, string value, int n)
    {
        int index = sourceStr.IndexOf(value); ;
        if (n == 1)
        {
            return index;
        }
        for (int i = 1; i < n; i += 1)
        {
            index = sourceStr.IndexOf(value, index + 1);
        }
        return index;
    }

方法二:使用正则表达式(缺点,不易阅读)

转载:https://www.codenong.com/186653/

public static class StringExtender
{
    /// <summary>
    /// 获取字符串第n次出现的索引
    /// </summary>
    /// <param name="sourceString">原始字符串</param>
    /// <param name="value">所要查询的字符串</param>
    /// <param name="n">第几次出现</param>
    /// <returns></returns>
    public static int NthIndexOf(this string sourceString, string value, int n)
    {
        Match m = Regex.Match(sourceString, "((" + Regex.Escape(value) + ").*?){" + n + "}");

        if (m.Success)
            return m.Groups[2].Captures[n - 1].Index;
        else
            return -1;
    }
}

方法三、四:带起始位

    public static int IndexOfNth3(string sourceStr, char value, int startIndex, int nth)
    {
        if (nth < 1)
            Debug.LogError("Param 'n' must be greater than 0!");
        var nResult = 0;
        for (int i = startIndex; i < sourceStr.Length; i++)
        {
            if (sourceStr[i] == value)
                nResult++;
            if (nResult == nth)
                return i;
        }
        return -1;
    }
    public static int IndexOfNth4(this string sourceStr, string value, int startIndex, int n)
    {
        if (n < 1)
            Debug.LogError("Param 'n' must be greater than 0!");
        if (n == 1)
            return sourceStr.IndexOf(value, startIndex);
        var idx = sourceStr.IndexOf(value, startIndex);
        if (idx == -1)
            return -1;
        return sourceStr.IndexOfNth4(value, idx + 1, --n);
    }

猜你喜欢

转载自blog.csdn.net/WenHuiJun_/article/details/129619504