Compare strings with characters

I want to compare a string with another string in C #, in this example

string Text1 = "123bob456"; string Text2 = "bobishere"; 

I want to say if more than three (or more) characters match in the sequence, then return true, in this case it will be true, since both of them contain "bob".
but I don’t know how to do this, could you help and excuse me if this is a recurring question that I know how to say it.

+4
source share
2 answers

Your problem is the longest common substring problem , which can be solved in time proportionally to the sum of the length of two strings. See Link for possible algorithms.

If you want to suffer a little from performance, you can make it easier by looking at each three-character sequence in the first line and searching for that sequence in the second. Here is an example (I am not very familiar with C #, so please forgive any syntax errors):

 for (int i = 0; i < s1.Length - 2; i++) if (s2.Contains(s1.Substring(i, 3))) return true; return false; 

Your choice will depend on your specific problem. I would try the second approach and reconsider if it is too slow.

+6
source

This extension works:

 public static bool ContainsSubstring(this string string1, string string2, int minLength, StringComparison comparison) { if (minLength <= 0) throw new ArgumentException("Minimum-length of substring must be greater than 0", "minLength"); if (string.IsNullOrEmpty(string1) || string1.Length < minLength) return false; if (string.IsNullOrEmpty(string2) || string2.Length < minLength) return false; for (int i = 0; i < string1.Length - minLength + 1; i++) { string part1 = string1.Substring(i, minLength); if (string2.IndexOf(part1, comparison) > -1) return true; } return false; } 

eg:

 string Text1 = "123bob456"; string Text2 = "bobishere"; bool contains = Text1.ContainsSubstring(Text2, 3, StringComparison.CurrentCultureIgnoreCase); // true 

Demo

+1
source

Source: https://habr.com/ru/post/1479176/


All Articles