获得两个字符串之间的共同点## [关闭]

问题描述 投票:0回答:3

我需要的是在两个单词之间得到共同点并得到差异。

例子:

场景1

  • word1 =见证
  • word2 =测试

将返回

  • 共同部分测试,差异imonial

情景2

  • word1 =测试
  • word2 =见证

将返回

  • 共同部分测试,差异imonial

场景3

  • word1 =见证
  • word2 =特斯拉

将返回

  • 共同部分Tes,差异timonial和la

这两个词的共同部分总是在开头。

换句话说,我需要保留单词的开头直到单词变得不同,而不是我需要得到差异。

我试图这样做,避免使用很多if和for。

感谢你们。

c# string linq
3个回答
2
投票
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();
    }
}

1
投票

LINQ替代方案:

string word1 = "Testimonial", word2 = "Tesla";

string common = string.Concat(word1.TakeWhile((c, i) => c == word2[i]));

string[] difference = { word1.Substring(common.Length), word2.Substring(common.Length) };

0
投票

您可以使用IntersectExcept来获取它:

static void Main(string[] args)
{
    var string1 = "Testmonial";
    var string2 = "Test";

    var intersect = string1.Intersect(string2);
    var except = string1.Except(string2);

    Console.WriteLine("Intersect");

    foreach (var r in intersect)
    {
        Console.Write($"{r} ");
    }

    Console.WriteLine("Except");

    foreach (var r in except)
    {
        Console.Write($"{r} ");
    }

    Console.ReadKey();
}

请注意,这是一个简单的解决方案。例如:如果更改字符串的顺序,则不起作用,例如:

"Test".Except("Testmonial");
© www.soinside.com 2019 - 2024. All rights reserved.