Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 790
Laz Nikolaj Andersen Avatar asked Dec 15 '22 10:12

Laz Nikolaj Andersen


2 Answers

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
like image 173
Hamid Pourjam Avatar answered Dec 17 '22 01:12

Hamid Pourjam


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.

like image 28
M.kazem Akhgary Avatar answered Dec 17 '22 00:12

M.kazem Akhgary