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.
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 can use following extension method which uses string.IndexOf
:
public static bool ContainsMoreThan(this string text, int count, string value, StringComparison comparison)
{
if (text == null) throw new ArgumentNullException("text");
if (string.IsNullOrEmpty(value))
return text != "";
int contains = 0;
int index = 0;
while ((index = text.IndexOf(value, index, text.Length - index, comparison)) != -1)
{
if (++contains > count)
return true;
index++;
}
return false;
}
Use it in the following way:
string text = "Lorem ipsum dolor sit amet, quo porro homero dolorem eu, facilisi inciderint ius in.";
bool containsMoreThanOnce = text.ContainsMoreThan(1, "dolor", StringComparison.OrdinalIgnoreCase); // true
It's a string extension and enables to pass the count
, the value
you search and the StringComparison
(for example to search case-insensitively).
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;
private bool MoreThanOnce(string full, string part)
{
var first = full.IndexOf(part);
return first!=-1 && first != full.LastIndexOf(part);
}