Click here to Skip to main content
15,900,906 members
Please Sign up or sign in to vote.
1.47/5 (5 votes)
See more:
how can i get difference between contents of two strings??
for example:

string test1 ="word1,word2,word3,word4";
string test2 ="word2,word4";

now i want difference between two strings as "word1,word3"

HELP!!
Posted
Comments
Ralf Meier 7-Aug-15 15:03pm    
You should tell more about your requirement.
It looks like you have comma seperated string-parts which should be compared. Am I right ?
In this case I would split the strings into their parts and then compare (by iterating / loop) if some parts are equal.
Perhaps you give some more information ...
PIEBALDconsult 7-Aug-15 15:05pm    
Look up Levenshtein Distance.
Afzaal Ahmad Zeeshan 7-Aug-15 15:19pm    
The answer even depends on which string you are trying to compare against. Then, on what you want to compare, which type of comparison and many more such cases arise.

As Raif has said, splitting them into arrays and checking each element with others might solve the riddle. But that is still not at all helpful.
Sergey Alexandrovich Kryukov 7-Aug-15 15:22pm    
Define "difference".
—SA

1 solution

This gets your requested result; however, the others (above) have very important questions that should be answered if you want a correct answer. If you are allowed to split the string up by commas, and you are looking for everything in test1 that is not in test2, then this will work, but if you switch test1 and test2, you'll get an empty string. If you add a unique element to test2, this code will not find it. This may not be what you're after.

C#
string test1 = "word1,word2,word3,word4";
string test2 = "word2,word4";

string result = string.Join(",", test1.Split(',').Except(test2.Split(',')));


If you wanted to find what was in test1 and not in test2, but also find what was in test2 and not in test1:

C#
string test1 = "word1,word2,word3,word4";
string test2 = "word2,word4,word5";
var lst1 = test1.Split(',');
var lst2 = test2.Split(',');
var listDistinct = lst1.Concat(lst2);
var result = string.Join(",",
                        listDistinct.Except(lst2)
                              .Concat(listDistinct.Except(lst1))
                        .OrderBy(x=> x));
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900