如何比较c#中两个字符串,其中一个字符串的开始部分是另一个字符串的结束部分



我有两个字符串,例如:

str1 = "CGGCAGTGGTAGTCTGAG" 
str2 = "TGAGCGCGCGCGCGCGCG"

我想得到两个字符串相同的部分"TGAG">

是吗?

public static string GetMatchPart(string str1, string str2, int maxMatchSize)
{
string tmp = string.Empty;
for (int i = maxMatchSize; i >= 0; i--)
{
tmp = str2.Substring(0, i);
if (str1.StartsWith(tmp) || str1.EndsWith(tmp))
{
return tmp;
}
tmp = str2.Substring(str2.Length-i, i);
if (str1.StartsWith(tmp) || str1.EndsWith(tmp))
{
return tmp;
}
}
return tmp;
}
static void Main(string[] args)
{
string str1 = "CGGCAGTGGTAGTCTGAG";
string str2 = "TGAGCGCGCGCGCGCGCG";
string result = GetMatchPart(str1, str2, 4);
}

结果字符串包含"TGAG",它查找其他字符串开头或结尾的最大部分。如果没有匹配,则返回一个空字符串。

编辑:我添加了一个maxMatchSize参数来解决你的速度问题。对于您提供的示例字符串,将其设置为4可以立即得到结果。我也考虑过使用str1.Length/2

希望这对你有帮助!

using System;

class string_comparison_equals

{
static void Main()

{
string str1 = "CGGCAGTGGTAGTCTGAG"; 
string str2 = "TGAGCGCGCGCGCGCGCG";

if (String.Equals(str1[-1:-4], str2[0:3])) or (String.Equals(str1[0:3], str2[-1:-4]))
{
Console.WriteLine("The strings have the same beginning and end");
}
else
{
Console.WriteLine("The strings are different");
}

Console.ReadLine();

}

}

结果应该是:

The strings have the same beginning and end

最新更新