user2279389
user2279389

Reputation: 89

String Comparisons with chars

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.

Upvotes: 4

Views: 145

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460350

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

Upvotes: 1

nullptr
nullptr

Reputation: 2284

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.

Upvotes: 6

Related Questions