如何计算特定字符在文本文件中出现在另一个特定字符之前的次数?

时间:2019-03-06 16:50:32

标签: c# .net text count character

是否有一种方法可以计算文本文件中某个特定字符出现在另一个特定字符之前的次数?

假设我在文本文件中写了以下内容:xxx * xxx〜xxx * xxx * xxx〜

我想计算字符“ *”出现在“〜”字符之前的次数,并重新计算“ *”字符直到下一个“〜”字符,依此类推。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

public static int FindCountOfCharBeforeAnotherChar(string text, char find, char findBefore)
{
    var indexOfFindBefore = text.IndexOf(findBefore);
    if (indexOfFindBefore < 1) return 0;
    var textBeforeMatch = text.Substring(0, indexOfFindBefore);
    return textBeforeMatch.Count(c => c == find);
}

[TestCase("aXa", 1)]
[TestCase("aaXa", 2)]
[TestCase("aaa", 0)]
[TestCase("Xaa", 0)]
public void FindsExpectedCharacterCount(string text, int expected)
{
    Assert.AreEqual(expected, FindCountOfCharBeforeAnotherChar(text, find:'a', findBefore:'X'));
}
相关问题