是否可以比较两个字符串,例如:
"North, South, East" == "North, East, South"
并基于
这一事实找到等价both contain "North"
或
both contain "South"
另一个例子
"North" == "North, South"
另外
"North" != "South"
显然,逗号分隔关键字符串以进行比较。不确定C#中是否有关键功能可以帮助解决这个问题? “包含”将不起作用,因为分隔值的顺序可能不同,即
"North, South" == "South, North"
任何对此的帮助都将非常感激。寻找一些专家C#指导!
答案 0 :(得分:1)
使用String.Split
从string[]
获取String
,其中每个标记由分隔符分隔,例如逗号:
var tokens1 = "North, South, East".Split(',').Select(s => s.Trim());
var tokens2 = "North, East, South".Split(',').Select(s => s.Trim());
我已使用Enumerable.Select
删除String.Trim
的前导或尾随空格。现在,您可以使用Intersect
+ Any
来检查是否存在公共交叉点:
bool anyIntersection = tokens1.Intersect(tokens2).Any();
答案 1 :(得分:1)
您可以使用Any()
这样写:
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
}
答案 2 :(得分:1)
你的意思是这样的,打印和#34;共同的字符串:南,东和#34;
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));