vigri vigri - 4 months ago 18
C# Question

Check if string contains substring more than once

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 hot. Not how many.

Answer

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;
Comments