C# third index of a character in a string

前端 未结 10 1966
甜味超标
甜味超标 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:06

    This has already been answered several very good ways - but I decided to try and write it using Expressions.

    private int? GetNthOccurrance(string inputString, char charToFind, int occurranceToFind)
    {
        int totalOccurrances = inputString.ToCharArray().Count(c => c == charToFind);
        if (totalOccurrances < occurranceToFind || occurranceToFind <= 0)
        {
            return null;
        }
    
        var charIndex =
            Enumerable.Range(0, inputString.Length - 1)
                .Select(r => new { Position = r, Char = inputString[r], Count = 1 })
                .Where(r => r.Char == charToFind);
    
    
        return charIndex
            .Select(c => new
            {
                c.Position,
                c.Char,
                Count = charIndex.Count(c2 => c2.Position <= c.Position)
            })
            .Where(r => r.Count == occurranceToFind)
            .Select(r => r.Position)
            .First();
    }
    

    and Tests to prove it too:

    Assert.AreEqual(0, GetNthOccurrance(input, 'h', 1)); 
    Assert.AreEqual(3, GetNthOccurrance(input, 'l', 2));
    Assert.IsNull(GetNthOccurrance(input, 'z', 1));
    Assert.IsNull(GetNthOccurrance(input, 'h', 10));
    

提交回复
热议问题