Is it possible to compare two strings such as:
"North, South, East" == "North, East, South"
and find equivalence, based on the fact that
both contain "North"
or
both contain "South"
Another example
"North" == "North, South"
Also
"North" != "South"
Obviously the comma seperates the key strings for comparison. Not sure if there is a key function in C# that could help with this? "Contains" will not work, as the order of the delimited values could be different, ie
"North, South" == "South, North"
Any help with this would be gratefully accepted. Looking for some expert C# guidance!
Use String.Split
to get a string[]
from the String
where each token is separated by a delimiter, for example the comma:
var tokens1 = "North, South, East".Split(',').Select(s => s.Trim());
var tokens2 = "North, East, South".Split(',').Select(s => s.Trim());
I have used Enumerable.Select
to remove leading or trailing spaces with String.Trim
. Now you can use Intersect
+ Any
to check if there's a common intersection:
bool anyIntersection = tokens1.Intersect(tokens2).Any();
You can write it using Any()
this way:
string NEWS = "North, South, East";
string NEW = "North, East, South";
var temp1 = NEWS.Split(',');
var temp2 = NEW.Split(',');
if (temp1.Any(x => temp2.Contains(x)))
{
// means equal
}
Do you mean something like this, which prints "Strings in common: South, East"
string s1 = "North, South, East";
string s2 = "East, West, South";
var strings1 = s1.Split(',').Select(s => s.Trim());
var strings2 = s2.Split(',').Select(s => s.Trim());
var stringsInCommon = strings1.Intersect(strings2);
Console.WriteLine("Strings in common: " + string.Join(", ", stringsInCommon));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.