Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find Count of Substring in string C#

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

like image 758
No Strings on Me Avatar asked Aug 27 '18 01:08

No Strings on Me


People also ask

How many substrings are in a string of length n?

Approach: The count of sub-strings of length n will always be len – n + 1 where len is the length of the given string.


2 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

like image 77
Saif Avatar answered Sep 19 '22 23:09

Saif


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.

like image 27
Petr Nohejl Avatar answered Sep 20 '22 23:09

Petr Nohejl