find Count of Substring in string C#

Viewed 13534

I am trying to find how many times the word "Serotonin" appears in the gathered web data but cannot find a method for finding the number of times.

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);



}

I can easily use the data from those methods 1 and 3 when I tell it what number in the index and method 2 would work but only works for chars not strings

I have checked online and on here but found nothing of finding the count of the StringToFind

6 Answers

Assume string is like this

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

then just use regex to find how many times word is matched in your test string like this

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

output would be 2

The solution int count = Regex.Matches(someString, potencialSubstring).Count;

did not work for me. Even thou I used Regex.Escape(str)

So I wrote it myself, it is quite slow, but the performance is not an issue in my app.

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;
}

Maybe someone will find this useful.

Improvement on @Petr Nohejl's excellent answer:

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;
}

This does not use Regex.Matches and probably has better performance and is more predictable.

See on .NET Fiddle

If you don't worry about performance, here are 3 alternative solutions:

int Count(string src, string target)
    => src.Length - src.Replace(target, target[1..]).Length;

int Count(string src, string target)
    => src.Split(target).Length - 1;

int Count(string src, string target)
    => Enumerable
        .Range(0, src.Length - target.Length + 1)
        .Count(index => src.Substring(index, target.Length) == target);

Oh yes, I have it now.

I will split() the array and get the length

2nd to that I will IndexOf until I return a -1

Thanks for help in the comments!

A possible solution would be to use Regex:

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