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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With