Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare strings for equality

I want to compare a collection of strings and return the the equal parts until a not equal part occurs. (and remove traling whitespace).

example:

List<string> strList = new List<string>
{
    "string xyz stop",
    "string abc stop",
    "string   qrt stop"
};

string result = GetEqualName(strList); // This should return "string"

I made the following method that works

string GetEqualName(IEnumerable<string> strList)
{
    string outString = "";
    bool firstTime = true;
    foreach (var subString in strList)
    {
        if (firstTime)
        {
            outString = subString;
            firstTime = false;
        }
        else
        {
            string stringBuilder = "";
            for (int i = 0; i < outString.Count(); i++)
            {
                if (outString[i] == subString[i])
                    stringBuilder = stringBuilder + outString[i];
                else
                    break;
            }
            outString = stringBuilder;
        }
    }
    outString = outString.TrimEnd(' '); // Remove traling whitespace
    return outString;
}

I just feel that this is something that can be done in a few lines and I am overdoing it. Do you guys have any suggestions?

like image 550
Daltons Avatar asked Dec 04 '25 23:12

Daltons


1 Answers

You can Zip two strings together, take the pairs that are equal, and then create a string of those characters.

public static string LargestCommonPrefix(string first, string second)
{
    return new string(first.Zip(second, Tuple.Create)
        .TakeWhile(pair => pair.Item1 == pair.Item2)
        .Select(pair => pair.Item1)
        .ToArray());
}

Once you've solved the problem for the case of combining two strings, you can easily apply it to a sequence of strings:

public static string LargestCommonPrefix(IEnumerable<string> strings)
{
    return strings.Aggregate(LargestCommonPrefix);
}
like image 181
Servy Avatar answered Dec 06 '25 14:12

Servy