c# - Showing the intersection between two strings -
i trying find intersection between 2 strings. example, if string 1 my car bad
, , string 2 my horse good
, return my is
. code:
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; }
but error system.linq.enumerable+d__92
1[system.string]`. explain what's going on, , how can fix it?
you're not seeing error - seeing qualified name of type of result
, system.linq.enumerable+d_921[system.string]
. default behavior tostring()
, unless overridden in inheriting class. see object.tostring().
to show results of intersection, can use string.join
, this:
test = string.join(" ", results);
which produce my is
.
note code posted wouldn't compile:
string[] m = string1.distinct(); string[] n = string2.distinct();
the above lines generated cannot implicitly convert type 'system.collections.generic.ienumerable<string>' 'string[]'
. adding .toarray()
1 way resolve this. full code below:
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; }
Comments
Post a Comment