vigri vigri - 2 months ago 14
C# Question

Check if string contains substring more than once

To search for a substring inside a string I can use the

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 hot. 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;