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
Approach: The count of sub-strings of length n will always be len – n + 1 where len is the length of the given string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With