Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string contains substring more than once

Tags:

c#

search

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.

like image 532
vigri Avatar asked Feb 20 '13 16:02

vigri


3 Answers

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;
like image 65
Ilya Ivanov Avatar answered Nov 01 '22 04:11

Ilya Ivanov


One line of code with RegEx:

return Regex.Matches(myString, "test").Count > 1;
like image 7
Doug S Avatar answered Nov 01 '22 05:11

Doug S


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;
like image 3
faceman Avatar answered Nov 01 '22 04:11

faceman