1

假设我有两个字符串:

"SomeTextHereThatIsTheSource"
"SomeTextHereThatIsCloseToTheSourceButNotTheSame"

是否有一种巧妙的 .net 方法可以知道文本的哪一部分是相同的(从头开始)。

所以在这个例子中,结果将是:

"SomeTextHereThatIs"
4

4 回答 4

3

您可以使用 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)  
于 2013-01-19T19:33:17.440 回答
2

我会说for在较短的字符串上循环,逐个字符比较是你最好的选择。它也可能是最快的。

// str1 is shorter or equal in length to str2:
for(int i=0; i < str1.Length; i++)
{
  if(str1[i] == str2[i])
   continue;

  return i;
}
于 2013-01-19T19:24:32.403 回答
0

使用简单的 while 循环来确定匹配长度:

int len = 0;
while (len < s1.Length && len < s2.Length && s1[len] == s2[len]) {
    len++;
}

如果您提前确定两个字符串的最小长度,您可以稍微改进一下

int minLength = Math.Min(s1.Length, s2.Length);
int len = 0;
while (len < minLength && s1[len] == s2[len]) {
    len++;
}
于 2013-01-19T19:38:09.890 回答
0

虽然它可能不是最优化的,但利用 astring也是IEnumerable<char>.

static string CommonPrefix(string string1, string string2) {
    var length = Enumerable.Zip(string1, string2, (a, b) => a == b).TakeWhile(a => a).Count();
    return string1.Substring(0, length);
}
于 2013-01-19T19:53:56.570 回答