Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Comparisons with chars

Tags:

string

c#

char

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

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

I want to say, if more that 3 (or more) chars match in sequence then return true, in this case it would be true as they both contain "bob".
but I do not know how to do this, could you please help and sorry if this is a repeated question I dint know how to word it.

like image 961
user2279389 Avatar asked Mar 25 '23 02:03

user2279389


2 Answers

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

If you're willing to take a bit of a performance hit, you can do it more simply by considering every sequence of 3 characters in the first string and searching for that sequence in the second. Here is an example (I'm 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 particular problem. I would try the second approach and revise if it is too slow.

like image 117
nullptr Avatar answered Apr 01 '23 19:04

nullptr


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

for example:

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

Demo

like image 35
Tim Schmelter Avatar answered Apr 01 '23 17:04

Tim Schmelter