get common prefix of two string

白昼怎懂夜的黑 提交于 2019-12-22 08:48:25

问题


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.


回答1:


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



回答2:


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.




回答3:


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




回答4:


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;
    }


来源:https://stackoverflow.com/questions/33709165/get-common-prefix-of-two-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!