说我有两个字符串:
"SomeTextHereThatIsTheSource"
"SomeTextHereThatIsCloseToTheSourceButNotTheSame"
是否有一种巧妙的.net方式可以知道文本的哪一部分是相同的(从头开始)。
因此,在此示例中,结果将是:
"SomeTextHereThatIs"
最佳答案
您可以使用TakeWhile:
string MatchFromStart(string s1, string s2)
{
if (s1 == null || s2 == null) return "";
var matchingArray = s1.TakeWhile((c, i) => { return i < s2.Length && c == s2[i]; });
return String.Join("", matchingArray);
}
然后使用它:
string s1 = "SomeTextHereThatIsTheSource";
string s2 = "SomeTextHereThat";
string s3 = "SomeTextHereThatIsCloseToTheSourceButNotTheSame";
Console.WriteLine(MatchFromStart(s1, s2)); // SomeTextHereThat
Console.WriteLine(MatchFromStart(s2, s1)); // SomeTextHereThat
Console.WriteLine(MatchFromStart(s3, s1)); // SomeTextHereThatIs
Console.WriteLine(MatchFromStart("", s1)); // (blank string)
Console.WriteLine(MatchFromStart(s3, "")); // (blank string)
Console.WriteLine(MatchFromStart(null, s1)); // (blank string)
Console.WriteLine(MatchFromStart(s2, null)); // (blank string)
关于c# - 找出多少个字符串匹配,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14417962/