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

标签 c# .net string

假设我有两个字符串:

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

相关文章:

.net - 如何编写适用于 .NET 3.5 紧凑框架和常规框架的类库?

c# - 如何检查特定IP地址是否连接到网络

string - 我试图在 matlab 中显示变量名称和它们的值的 num2str 表示

c# - 无法在可移植类库中使用 linq 查询找到 xml 元素

c# - 如何在不创 build 置的情况下让可执行文件在其他计算机上运行,

c# - 如何在 asp.net mvc 4 中为 select2 字段提供强制字段验证

java - 使用正则和正则表达式查找所有可能出现的情况

c# - 无法从外部设备获取目录

.net - app.config appSettings 文件属性中的环境变量

c# - 在 C# : Add Quotes around string in a comma delimited list of strings 中