【发布时间】:2021-07-14 09:10:52
【问题描述】:
我有两个要比较的字符串变量。
var compareA = "something.somethingelse.another.something2"
var compareB = "*.another.something2"
我想比较一下,结果是:是的。
var compareC = "something.somethingelse.*"
与 compareA 相比,结果也应该是:True。
当然,两个变量都可以包含 N 个点这一事实也使任务复杂化。 你会如何开始为他?
我试过这个:
static void Main(string[] args)
{
var A = CompareString("*.something", "other.Another.something"); //I need this is true!
var B = CompareString("something.Value.Other.*", "something.Value.Other.SomethingElse"); //I need this is true
var C = CompareString("something.Value.Other", "something.Value.Other.OtherElse"); //I need this is False
var D = CompareString("*.somethingElse", "other.another.Value"); //I Need this is false
Console.WriteLine("It is need True: {0}", A);
Console.WriteLine("It is need True: {0}", B);
Console.WriteLine("It is need False: {0}", C);
Console.WriteLine("It is need False: {0}", D);
}
private static bool CompareString(string first, string second)
{
var resume = false;
var firstSplit = first.Split('.');
var secondSplit = second.Split('.');
foreach (var firstItem in firstSplit)
{
foreach (var secondItem in secondSplit)
{
if (firstItem == "*" || secondItem == "*" || string.Equals(firstItem.ToLower(), secondItem.ToLower()))
{
resume = true;
}
else
{
resume = false;
}
}
}
return resume;
}
结果很好,但我觉得可以换个方式,推理可能有误。
【问题讨论】:
-
到目前为止,您自己尝试过什么?你遇到了什么问题?你研究了什么?请编辑您的问题以包含更多信息。我推荐taking the tour,以及阅读how to ask a good question 和what's on topic。另外:你目前对什么应该匹配和什么不匹配的描述非常模糊。
-
也许使用正则表达式?
-
那么看看你的例子,你基本上是在比较字符串并检查 1 是否包含另一个,并添加通配符?
-
如果 compareC 是 "something.another" 并与 compareA 比较怎么办?这是真的还是假的?
-
@sr28 如果 compareC 是 "something.another" 答案是 false
标签: c# string split compare equals