获取两个字符串之间的共同部分C# [英] Get common part between two strings c#
本文介绍了获取两个字符串之间的共同部分C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要的是获得两个单词之间的共同部分,并获得差异.
What I need is to get the common part between two words and get the differences too.
示例:
场景1
- word1 = 推荐
- word2 = 测试
- word1 = Testimonial
- word2 = Test
会回来
- 公用部分测试,差异个人
- Common part Test, difference imonial
场景2
- word1 = 测试
- word2 = 推荐
- word1 = Test
- word2 = Testimonial
会回来
- 公用部分测试,差异个人
- Common part Test, difference imonial
场景3
- word1 = 推荐
- word2 = 特斯拉
- word1 = Testimonial
- word2 = Tesla
会回来
- 公用部分 Tes ,差异 timonial 和 la
- Common part Tes, difference timonial and la
两个单词的共同部分总是在开头.
The common part of both words are always on the beginning.
换句话说,我需要保留单词的开头,直到单词变得不同为止,而不是需要获得差异.
In other words, I need to preserve the begin of the word until the words get different, than I need to get the differences.
我正试图避免使用很多if和for.
I'm trying to do that avoid using a lot of if's and for's.
谢谢你们.
推荐答案
class Program
{
static void Main(string[] args)
{
string word1 = "Testimonial";
string word2 = "Tesla";
string common = null;
string difference1 = null;
string difference2 = null;
int index = 0;
bool same = true;
do
{
if (word1[index] == word2[index])
{
common += word1[index];
++index;
}
else
{
same = false;
}
} while (same && index < word1.Length && index < word2.Length);
for (int i = index; i < word1.Length; i++)
{
difference1 += word1[i];
}
for (int i = index; i < word2.Length; i++)
{
difference2 += word2[i];
}
Console.WriteLine(common);
Console.WriteLine(difference1);
Console.WriteLine(difference2);
Console.ReadLine();
}
}
这篇关于获取两个字符串之间的共同部分C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文