C# third index of a character in a string

前端 未结 10 1967
甜味超标
甜味超标 2020-12-06 17:18

is there a command that can get the third index of a character in a string? For example:

error: file.ext: line 10: invalid command [test:)]

10条回答
  •  孤城傲影
    2020-12-06 18:10

    Here is a recursive implementation (for string not char) - as an extension method, mimicing the format of the framework method(s).

    All you need to do is change 'string value' to 'char value' in the extension method and update the tests accordingly and it will work... I'm happy to do that and post it if anyone is interested?

    public static int IndexOfNth(
        this string input, string value, int startIndex, int nth)
    {
        if (nth < 1)
            throw new NotSupportedException("Param 'nth' must be greater than 0!");
        if (nth == 1)
            input.IndexOf(value, startIndex);
        return
            input.IndexOfNth(value, input.IndexOf(value, startIndex) + 1, --nth);
    }
    

    Also, here are some (MBUnit) unit tests that might help you (to prove it is correct):

    [Test]
    public void TestIndexOfNthWorksForNth1()
    {
        const string input = "foo
    bar
    baz
    "; Assert.AreEqual(3, input.IndexOfNth("
    ", 0, 1)); } [Test] public void TestIndexOfNthWorksForNth2() { const string input = "foo
    whatthedeuce
    kthxbai
    "; Assert.AreEqual(21, input.IndexOfNth("
    ", 0, 2)); } [Test] public void TestIndexOfNthWorksForNth3() { const string input = "foo
    whatthedeuce
    kthxbai
    "; Assert.AreEqual(34, input.IndexOfNth("
    ", 0, 3)); }

提交回复
热议问题