我找到了一个不错的扩展方法,可以将value的第N个出现在某些input字符串中:

public static int IndexOfNth(this string input, string value, int startIndex, int nth)
{
    if (nth < 1)
        throw new ArgumentException("Can not find the zeroth index of substring in string. Must start with 1");
    if (nth == 1)
        return input.IndexOf(value, startIndex, StringComparison.Ordinal);
    var idx = input.IndexOf(value, startIndex, StringComparison.Ordinal);
    if (idx == -1)
        return -1;
    return input.IndexOfNth(value, idx + value.Length, --nth);
}


我需要下一个,但是我自己不能转换它:

IndexOfNthFromEnd(this string input, string value, int nth)


它应该从字符串的末尾找到第N个出现的索引。例如:

IndexOfNthFromEnd("-!-!----", "!", 2) // = 1;
IndexOfNthFromEnd("-!-!----", "!", 1) // = 3;
IndexOfNthFromEnd("-!-!----", "-!", 2) // = 0;
IndexOfNthFromEnd("-!-!----", "-!", 1) // = 2;

最佳答案

public static int IndexOfNthFromEnd(this string input, string value, int startIndex, int nth)
{
    if (nth < 1)
        throw new ArgumentException("Can not find the zeroth index of substring in string. Must start with 1");
    var idx = input.LastIndexOf(value, startIndex, StringComparison.Ordinal);
    if (idx == -1 || nth == 1)
        return idx;
    return input.IndexOfNthFromEnd(value, idx - value.Length, --nth);
}


请注意,您原来的IndexOfNth应该确实可以:

return input.IndexOfNth(value, idx + value.Length, --nth);


否则,对于:"abababa".IndexOfNth("bab", 0, 2)它返回3,当它应为-1时,因为bab仅在字符串中出现一次。

10-08 15:51