Aaron
Aaron

Reputation: 812

String cannot contain any part of another string .NET 2.0

I'm looking for a simple way to discern if a string contains any part of another string (be that regex, built in function I don't know about, etc...). For Example:

string a = "unicorn";
string b = "cornholio";
string c = "ornament";
string d = "elephant";

if (a <comparison> b)
{
    // match found ("corn" from 'unicorn' matched "corn" from 'cornholio')
}

if (a <comparison> c)
{
    // match found ("orn" from 'unicorn' matched "orn" from 'ornament')
}

if (a <comparison> d)
{
    // this will not match
}

something like if (a.ContainsAnyPartOf(b)) would be too much to hope for.

Also, I only have access to .NET 2.0.

Thanks in advance!

Upvotes: 0

Views: 276

Answers (4)

great_llama
great_llama

Reputation: 11749

I think you're looking for this implementation of longest common substring?

Upvotes: 3

Benjamin Podszun
Benjamin Podszun

Reputation: 9837

Your best bet, according to my understanding of the question, is to compute the Levenshtein (or related values) distance and compare that against a threshold.

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245499

Your requirements are a little vague.

You need to define a minimum length for the match...but implementing an algorithm shouldn't be too difficult when you figure that part out.

I'd suggest breaking down the string into character arrays and then using tail recursion to find matches for the parts.

Upvotes: 0

juharr
juharr

Reputation: 32296

This method should work. You'll want to specify a minimum length for the "part" that might match. I'd assume you'd want to look for something of at least 2, but with this you can set it as high or low as you want. Note: error checking not included.

public static bool ContainsPartOf(string s1, string s2, int minsize)
{
    for (int i = 0; i <= s2.Length - minsize; i++)
    {
        if (s1.Contains(s2.Substring(i, minsize)))
            return true;
    }
    return false;
}

Upvotes: 5

Related Questions