简体   繁体   中英

Is there a way to compare two strings in C# and get the differences only?

I am trying to compare two string in C# and get the differences between them ie words which are not present in the other string ignoring cases and commas just focusing on the words. If one string contains two or multiple the and the second string has one the , it means this will be disregarded as it exists in both. Example I have two strings like below;

  1. Cat meet's a dog
  2. Cat meet's a dog and a bird

The difference between those two strings is and bird because it does not exist in the first one or vise versa and I want to get those two words and bird either in a List or a new string with spaces between them and in other words I want the words which are not present in the other string. Is there a way this can be done in C#?

I wrote you a simple solution, hope it will help -

The main method is called 'Difference' it receive 2 strings to compare and return an object called StringDiff. It runs 2 loops, first comparing between the two strings char by char and then adding the rest of the longer string.

The 'StringDiff' object is a class with 2 char lists that represnt the differences of each string.

In the main method i use String.join to convert the char lists to a string and print it.

  internal class Program
    {
        static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine("enter first string");
                string firstString = Console.ReadLine();
                Console.WriteLine("enter second string");
                string secondString = Console.ReadLine();
                StringsDiff _stringsDiff = Difference(firstString, secondString);
                Console.WriteLine(
                $"fist string difference: {string.Join("", _stringsDiff._diffList1)} / second string difference: {string.Join("", _stringsDiff._diffList2)}");
                Console.WriteLine("/////////////////////////////////////");
            }
        }

        private static StringsDiff Difference(string firststring, string secondstring)
        {
            StringsDiff _stringsDiff = new StringsDiff();
            char[] _firstStringArray = firststring.ToCharArray();
            char[] _secondStringArray = secondstring.ToCharArray();
            int lenght;
            
            if (_firstStringArray.Length > _secondStringArray.Length)
            {
                lenght = _secondStringArray.Length;
                
                for (int i = 0; i < lenght; i++)
                {
                    if (!_firstStringArray[i].Equals(_secondStringArray[i]))
                    {
                        _stringsDiff._diffList1.Add(_firstStringArray[i]);
                        _stringsDiff._diffList2.Add(_secondStringArray[i]);
                    }
                }



                for (int i = _secondStringArray.Length; i < _firstStringArray.Length; i++)
                {
                    _stringsDiff._diffList1.Add(_firstStringArray[i]);
                }

            }
            else
            {
                lenght = _firstStringArray.Length;

                for (int i = 0; i < lenght; i++)
                {
                    if (!_firstStringArray[i].Equals(_secondStringArray[i]))
                    {
                        _stringsDiff._diffList1.Add(_firstStringArray[i]);
                        _stringsDiff._diffList2.Add(_secondStringArray[i]);
                    }
                }

                for (int i = _firstStringArray.Length; i < _secondStringArray.Length; i++)
                {
                    _stringsDiff._diffList2.Add(_secondStringArray[i]);
                }
            }

            return _stringsDiff;
        }

        class StringsDiff
        {
            public List<char> _diffList1 = new List<char>();
            public List<char> _diffList2 = new List<char>();
        }
    }

Remember to use "string.join" to connect the lists objects if you need a string.

Here's a way using LINQ. You don't need the "ToList()" part, but you mentioned that as one form of output you'd want:

string str1 = "Cat meet's a dog";
string str2 = "Cat meet's a dog and a bird";
string[] str1Words = str1.ToLower().Split(' ');
string[] str2Words = str2.ToLower().Split(' ');
var uniqueWords = str2Words.Except(str1Words).Concat(str1Words.Except(str2Words)).ToList();

// Do whatever you want with uniqueWords instead
Console.WriteLine($"output: {String.Join(" ", uniqueWords)}");

@ngdeveloper. This is my variant of your solution (had to post it in a separate answer because of the length):

private static StringsDiff Difference(string firststring, string secondstring)
{
    StringsDiff _stringsDiff = new StringsDiff();
    char[] _firstStringArray = firststring.ToCharArray();
    char[] _secondStringArray = secondstring.ToCharArray();
    int shortestLenght;
    int longestLenght;
    bool firstIsLongest;

    if (_firstStringArray.Length > _secondStringArray.Length)
    {
        firstIsLongest = true;
        shortestLenght = _secondStringArray.Length;
        longestLenght = _firstStringArray.Length;
    }
    else
    {
        firstIsLongest = false;
        shortestLenght = _firstStringArray.Length;
        longestLenght = _secondStringArray.Length;
    }
    
    for (int i = 0; i < shortestLenght; i++)
    {
        if (!_firstStringArray[i].Equals(_secondStringArray[i]))
        {
            _stringsDiff._diffList1.Add(_firstStringArray[i]);
            _stringsDiff._diffList2.Add(_secondStringArray[i]);
        }
    }
    for (int i = shortestLenght; i < longestLenght; i++)
    {
        if (firstIsLongest)
            _stringsDiff._diffList1.Add(_firstStringArray[i]);
        else
            _stringsDiff._diffList2.Add(_secondStringArray[i]);
    }
    return _stringsDiff;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM