在字符串 C# 中查找子字符串的计数

find Count of Substring in string C#

我试图找出单词 "Serotonin" 在收集的网络数据中出现了多少次,但找不到找到次数的方法。

IEnumerator OnMouseDown()
{


    string GatheredData;
    StringToFind = "Serotonin"

    string url = "https://en.wikipedia.org/wiki/Dopamine";

    WWW www = new WWW(url);
    yield return www;
    GatheredData = www.text;


    //Attempted methods below

    M1_count = GatheredData.Contains(StringToFind);

    M1_count = GatheredData.Count(StringToFind);

    M1_count = GatheredData.IndexOf(StringToFind);



}

当我告诉它索引中的什么数字和方法 2 可以工作但仅适用于字符而非字符串时,我可以轻松地使用这些方法 1 和 3 中的数据

我已经在网上和这里进行了检查,但没有找到 StringToFind 的计数

哦,是的,我现在有了。

我将 split() 数组并获取长度

第二个我将 IndexOf 直到我 return a -1

感谢评论中的帮助!

一个可能的解决方案是使用正则表达式:

var count = Regex.Matches(GatheredData.ToLower(), String.Format("\b{0}\b", StringToFind)).Count;

假设字符串是这样的

string test = "word means collection of chars, and every word has meaning";

然后只需使用正则表达式查找单词在您的 test 字符串中匹配的次数

int count = Regex.Matches(test, "word").Count;

输出将是 2

解决方法 int count = Regex.Matches(someString, potencialSubstring).Count;

对我不起作用。即使你我用 Regex.Escape(str)

所以我自己写的,速度很慢,但是在我的应用程序中性能不是问题。

private static List<int> StringOccurencesCount(String haystack, String needle, StringComparison strComp)
{
  var results = new List<int>();
  int index = haystack.IndexOf(needle, strComp);
  while (index != -1)
  {
    results.Add(index);
    index = haystack.IndexOf(needle, index + needle.Length, strComp);
  }
  return results;
}

也许有人会觉得这很有用。

改进@Petr Nohejl 的出色回答:

public static int Count (this string s, string substr, StringComparison strComp = StringComparison.CurrentCulture)
{
    int count = 0, index = s.IndexOf(substr, strComp);
    while (index != -1)
    {
        count++;
        index = s.IndexOf(substr, index + substr.Length, strComp);
    }
    return count;
}

这不使用 Regex.Matches 并且可能具有更好的性能并且更可预测。

See on .NET Fiddle