To search for a substring inside a string I can use the contains()
function.
But how can I check if a string contains a substring more than once?
To optimize that: For me it is sufficient to know that there is more than one result not how many.
Try to take advantage of fast IndexOf
and LastIndexOf
string methods. Use next code snippet. Idea is to check if first and last indexes are different and if first index is not -1, which means string is present.
string s = "tytyt";
var firstIndex = s.IndexOf("tyt");
var result = firstIndex != s.LastIndexOf("tyt") && firstIndex != -1;
One line of code with RegEx:
return Regex.Matches(myString, "test").Count > 1;
You could also use the Regex class. msdn regex
int count;
Regex regex = new Regex("your search pattern", RegexOptions.IgnoreCase);
MatchCollection matches = regex.Matches("your string");
count = matches.Count;
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