首页 > 解决方案 > 如何计算特定字符在其他特定字符第一次出现之前出现的频率?

问题描述

我有一个stringasdafahxlkax

我如何计算a在第一次出现之前出现 3 次x

谢谢。

标签: c#stringchar

解决方案


尝试:

public int CountBeforeChar(char toCount, char beforeChar, string testString)
{
  // Handle situation where we cannot find beforeChar in testString
  var idx = testString.IndexOf(beforeChar);
  idx = idx == -1 ? testString.Length - 1 : idx;
  return testString
    // Take substring until first occurence of "beforeChar"
    .Substring(0, idx)
    // Count all occurences of desired character in that substring
    .Count(ch => ch == toCount);
}

推荐阅读