Laz Nikolaj Andersen
Laz Nikolaj Andersen

Reputation: 751

get common prefix of two string

I am trying to compare two string in C# but I cant find a way to get the result I need without building something myself.

The strings:

TestasdOne
TestasdTwo

The result:

Testasd

I tried linq but could not get it to work. I tried Google.

Thanks in advance.

Upvotes: 5

Views: 2695

Answers (4)

Zverev Evgeniy
Zverev Evgeniy

Reputation: 3712

Here is a solution for an arbitrary array of strings and with some optimization. I do not compose the result on the fly but calculate the length instead.

    private static string GetCommonPrefix(params string[] values)
    {
        string result = string.Empty;
        int? resultLength = null;

        if (values != null)
        {
            if (values.Length > 1)
            {
                var min = values.Min(value => value.Length);

                for (int charIndex = 0; charIndex < min; charIndex++)
                {
                    for (int valueIndex = 1; valueIndex < values.Length; valueIndex++)
                    {
                        if (values[0][charIndex] != values[valueIndex][charIndex])
                        {
                            resultLength = charIndex;
                            break;
                        }
                    }

                    if (resultLength.HasValue)
                    {
                        break;
                    }
                }

                if (resultLength.HasValue &&
                    resultLength.Value > 0)
                {
                    result = values[0].Substring(0, resultLength.Value);
                }
            }
            else if (values.Length > 0)
            {
                result = values[0];
            }
        }

        return result;
    }

Upvotes: 1

Emmanuel DURIN
Emmanuel DURIN

Reputation: 4913

A solution could be to add an extension method to LInq that would work for strings, and any IEnumerable<T>

This is the kind of small functions that are fast to write when you feel they miss in Linq.

public static class CommonPartExtension
{
    public static IEnumerable<T> CommonPart<T>(this IEnumerable<T> source1, 
                                                    IEnumerable<T> source2)
    {
        IEnumerator<T> enumerator1 = source1.GetEnumerator();
        IEnumerator<T> enumerator2 = source2.GetEnumerator();
        while( enumerator1.MoveNext() && enumerator2.MoveNext())
        {
            if ( enumerator1.Current.Equals(enumerator2.Current) )
                yield return enumerator2.Current;
            else
                yield break ;
        }
    }
}

Usage :

        string s1 = "TestasdOne";
        string s2 = "TestasdTwo";
        Console.WriteLine("CommonPart " +
            new String( s1.CommonPart(s2).ToArray()));

Regards

Upvotes: 2

Hamid Pourjam
Hamid Pourjam

Reputation: 20754

Here is the non-linq version which is more efficient, clear and readable

public static string CommonPrefix(string a, string b)
{
    if (a == null)
        throw new ArgumentNullException(nameof(a));

    if (b == null)
        throw new ArgumentNullException(nameof(b));

    var min = Math.Min(a.Length, b.Length);
    var sb = new StringBuilder(min);
    for (int i = 0; i < min && a[i] == b[i]; i++)
        sb.Append(a[i]);

    return sb.ToString();
}

use it like

Console.WriteLine(CommonPrefix("TestasdOne", "TestasdTwo")); //Testasd

Upvotes: 6

M.kazem Akhgary
M.kazem Akhgary

Reputation: 19149

Using linq you can do this.

string str1 = "TestasdOne";
string str2 = "TestasdTwo";

string similar = string.Join("", str1.TakeWhile((ch, i) => i < str2.Length && str2[i] == ch));

This will take the characters of first string while its characters are equal to characters of second string at same index.

Upvotes: 4

Related Questions