【问题标题】:find Count of Substring in string C#在字符串 C# 中查找子字符串的计数
【发布时间】:2019-02-01 12:46:05
【问题描述】:

我试图找出“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 的计数

【问题讨论】:

标签: c# unity3d count substring indexof


【解决方案1】:

哦,是的,我现在有了。

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

第二次,我将 IndexOf 直到我返回 -1

感谢 cmets 的帮助!

【讨论】:

  • 这行得通,但上面的正则表达式解决方案要简单得多。
【解决方案2】:

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

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

【讨论】:

  • 您可能想改用Regex.Escape(StringToFind)。还可能值得一提的是\b 需要一个边界,所以SerotoninSerotonin 不会匹配,但Serotonin Serotonin 会匹配。在OP想要的情况下,我认为这没关系:)
  • 没错,我的答案是他真正需要的 :) 但谢谢约翰!
【解决方案3】:

假设字符串是这样的

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

然后只需使用正则表达式来查找您的test 字符串中的单词匹配次数,如下所示

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

输出将是2

【讨论】:

  • 我刚试过你的方法,效果很好,谢谢!
  • 使用:Regex.Escape(str) 以确保它可以处理所有输入
【解决方案4】:

解决方案 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;
}

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

【讨论】:

  • 恭喜,您刚刚发明了方轮;-) 正则表达式解决方案有效,但“potencialSubstring”是正则表达式模式。 Matches (string input, string pattern);Regex.Escape 不会转义所有可能的字符。如果你想要一个替代方案,为什么不使用string.Split,那么你不需要转义你的potencialSubstring。
【解决方案5】:

改进@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

【讨论】:

    猜你喜欢
    • 2012-02-21
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多