Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two strings and get the difference

Tags:

c#

How can i compare two strings in c# and gets the difference?

for example:

String1 : i have a car

string2 : i have a new car bmw

result: new, bmw

like image 222
Luis Avatar asked Jul 27 '10 13:07

Luis


People also ask

How do you compare two strings to return the difference?

Using String.equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.

Can you use == to compare two strings?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

How do you compare two strings together?

The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.


2 Answers

You need to make sure the larger set is on the left hand side of the Except (not sure if there is a pure Linq way to achieve that):

    static void Main(string[] args)     {         string s1 = "i have a car a car";         string s2 = "i have a new car bmw";          List<string> diff;         IEnumerable<string> set1 = s1.Split(' ').Distinct();         IEnumerable<string> set2 = s2.Split(' ').Distinct();          if (set2.Count() > set1.Count())         {             diff = set2.Except(set1).ToList();         }         else         {             diff = set1.Except(set2).ToList();         }     } 
like image 51
Mitch Wheat Avatar answered Sep 28 '22 09:09

Mitch Wheat


Based off your question (It is a bit vague.) this should work.

var first = string1.Split(' '); var second = string2.Split(' '); var primary = first.Length > second.Length ? first : second; var secondary = primary == second ? first : second; var difference = primary.Except(secondary).ToArray(); 

At the top of your file make sure you include:

using System.Linq; 
like image 40
ChaosPandion Avatar answered Sep 28 '22 09:09

ChaosPandion