c# - C# - 显示两个字符串之间的交集

我试图找到两个字符串之间的交集。例如,如果字符串之一为 my car is bad,第二个是 my horse is good会返回my is,这是我的代码:


 public static string intersection2(string x1, string x2)


{


 string[] string1 = x1.Split(\' \');


string[] string2 = x2.Split(\' \');


string[] m = string1.Distinct();


 string[] n = string2.Distinct();


 string Test;


 var results = m.Intersect(n,StringComparer.OrdinalIgnoreCase);


 Test = results.ToString();


 return Test;



}



但是,我得到错误System.Linq.Enumerable+d__92 1[System.String] `,谁能解释下发生了什么,以及我该如何修复它?

时间:

System.Linq.Enumerable+d_921[System.String]这是ToString()的默认行为,除非它在继承类中被重写,请参见Object.ToString() 。

要显示交集的结果,你可以使用String.Join,如下所示:


Test = String.Join("", results);



将产生my is

请注意,你发布的代码不能编译:


string[] m = string1.Distinct();


string[] n = string2.Distinct();



上面的行产生了一个Cannot implicitly convert type \'System.Collections.Generic.IEnumerable<string>\' to \'string[]\'添加.ToArray()是解决此问题的一种方法,下面的完整代码:


public static string intersection2(string x1, string x2)


{



 string[] string1 = x1.Split(\' \');


 string[] string2 = x2.Split(\' \');


 string[] m = string1.Distinct().ToArray();


 string[] n = string2.Distinct().ToArray();


 string Test;


 var results = m.Intersect(n, StringComparer.OrdinalIgnoreCase);


 Test = String.Join("", results);


 return Test;


}



你的逻辑没问题,你可以通过修改一点来使它工作,


public static string intersection2(string x1, string x2)


{


 string[] string1 = x1.Split(\' \');


 string[] string2 = x2.Split(\' \');


 var m = string1.Distinct();


 var n = string2.Distinct();



 var results = m.Intersect(n, StringComparer.OrdinalIgnoreCase);


 //The result is a list of string, so we just have to concat them


 var test ="";


 foreach(var k in results) test += k +"";


 return test;


}



fiddle :https://dotnetfiddle.net/joO0d9

这个程序得到两个字符串的交集(假设允许重复)


public String getIntersection(String s1, String s2) {


 String common ="";


 for (int i = 0; i < s1.length(); i++) {


 for (int j = 0; j < s2.length(); j++) {


 if (s1.length() == 0 || s1.length() == 0)


 return common;


 if (s1.charAt(i) == s2.charAt(j)) {


 common = common + s1.charAt(i);


 // delete character from each if there is a match


 s1 = s1.substring(0, i) + s1.substring(i + 1);


 s2 = s2.substring(0, j) + s2.substring(j + 1);


 i = -1;


 break;


 }


 }


 }


 return common;


}



...