gpt4 book ai didi

c# - 找出有多少字符串匹配

转载 作者:太空宇宙 更新时间:2023-11-03 20:19:41 25 4
gpt4 key购买 nike

假设我有两个字符串:

"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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com