Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any Framework functions helping to find the longest common starting substring of multiple strings?

Tags:

c#

I have a list of strings (which represent paths and) which should all have a common beginning (root path). I need to get that common beginning.

That's just a couple of lines to throw together, but I have the nagging feeling that this must be thrown together a million times a year and that there might be an algorithm in the framework that can be used for that, but couldn't find something.
Also, I suppose this has been asked on SO before, but I came up dry.

Any hints?

like image 856
sbi Avatar asked Dec 16 '25 19:12

sbi


1 Answers

If anyone is interested, here's what I came up with:

    public static string GetCommonStartingSubString(IList<string> strings)
    {
        if (strings.Count == 0)
            return "";
        if (strings.Count == 1)
            return strings[0];
        int charIdx = 0;
        while (IsCommonChar(strings, charIdx))
            ++charIdx;
        return strings[0].Substring(0, charIdx);
    }
    private static bool IsCommonChar(IList<string> strings, int charIdx)
    {
        if(strings[0].Length <= charIdx)
            return false;
        for (int strIdx = 1; strIdx < strings.Count; ++strIdx)
            if (strings[strIdx].Length <= charIdx 
             || strings[strIdx][charIdx] != strings[0][charIdx])
                return false;
        return true;
    }
like image 90
sbi Avatar answered Dec 19 '25 07:12

sbi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!