获取两个字符串的通用前缀 [英] get common prefix of two string
本文介绍了获取两个字符串的通用前缀的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在C#中比较两个字符串,但是我无法找到一种无需自己构建东西即可获得所需结果的方法.
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.
字符串:
TestasdOne
TestasdTwo
TestasdOne
TestasdTwo
结果:
Testasd
Testasd
我尝试了linq,但无法正常工作. 我尝试过Google.
I tried linq but could not get it to work. I tried Google.
提前谢谢.
推荐答案
以下是非linq版本,它更加有效,清晰和可读
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();
}
喜欢使用
Console.WriteLine(CommonPrefix("TestasdOne", "TestasdTwo")); //Testasd
这篇关于获取两个字符串的通用前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文