是否可以比较 "North, South, East" 和 "North, East, South" 并找到等价性?
Is it possible to compare "North, South, East" and "North, East, South" and find equivalence?
是否可以比较两个字符串,例如:
"North, South, East" == "North, East, South"
并根据
这一事实找到等价性
both contain "North"
或
both contain "South"
另一个例子
"North" == "North, South"
还有
"North" != "South"
显然逗号分隔了用于比较的关键字符串。不确定 C# 中是否有一个关键函数可以帮助解决这个问题? "Contains" 将不起作用,因为分隔值的顺序可能不同,即
"North, South" == "South, North"
如有任何帮助,我们将不胜感激。正在寻找 C# 专家指导!
使用 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();
你可以这样写 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
}
你的意思是这样的,它打印 "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));
是否可以比较两个字符串,例如:
"North, South, East" == "North, East, South"
并根据
这一事实找到等价性both contain "North"
或
both contain "South"
另一个例子
"North" == "North, South"
还有
"North" != "South"
显然逗号分隔了用于比较的关键字符串。不确定 C# 中是否有一个关键函数可以帮助解决这个问题? "Contains" 将不起作用,因为分隔值的顺序可能不同,即
"North, South" == "South, North"
如有任何帮助,我们将不胜感激。正在寻找 C# 专家指导!
使用 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();
你可以这样写 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
}
你的意思是这样的,它打印 "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));