获得两个字符串之间的区别 [英] Get difference between two strings.

查看:95
本文介绍了获得两个字符串之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何区分两个字符串的内容?

例如:



string test1 =word1,word2, word3,word4;

string test2 =word2,word4;



现在我希望两个字符串之间的差异为word1,word3



HELP !!

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!!

推荐答案

这可以获得您要求的结果;然而,如果你想要一个正确的答案,其他人(上面)有非常重要的问题应该回答。如果允许你用逗号分割字符串,并且你正在查找test1中不在test2中的所有内容,那么这将有效,但如果你切换test1和test2,你将得到一个空字符串。如果您向test2添加一个唯一元素,则此代码将不会找到它。这可能不是你想要的。



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.

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

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





如果你想找到test1中的内容而不是test2中的内容,还要查找test2中的内容而不是test1:





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

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));


这篇关于获得两个字符串之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆