获取字符串第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);
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值