Erick Gallani Erick Gallani - 1 month ago 5
C# Question

Get common part between two strings c#

What I need is to get the common part between two words and get the differences too.

Examples:

Scenario 1


  • word1 = Testimonial

  • word2 = Test



Will return


  • Common part Test, difference imonial



Scenario 2


  • word1 = Test

  • word2 = Testimonial



Will return


  • Common part Test, difference imonial



Scenario 3


  • word1 = Testimonial

  • word2 = Tesla



Will return


  • 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.

I'm trying to do that avoid using a lot of if's and for's.

Thank you guys.

Answer
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();
    }
}