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
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.
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.
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.
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(); } }
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With