我有一个比较两个字符串并报告第一个不同字符的函数:
public static int Diff(this string str1, string str2)
{
try
{
if (str1 == null || str2 == null)
return 0;
int index = str1.Zip(str2, (c1, c2) => c1 == c2).TakeWhile(b => b).Count();
return index;
}
catch (Exception)
{
return 0;
}
}
所以所有的魔法都在这里:
int index = str1.Zip(str2, (c1, c2) => c1 == c2).TakeWhile(b => b).Count();
假设我们有两个字符串:
INPUT,1,1,0,0,0,0,0,0,0,0,0,0
INPUT,?,?,1,?,?,?,?,?,?,?,?,?
01234567890
所以考虑到所有的字符,第一个不同的是?所以答案是6(从0开始)。一切正常。
现在我想介绍一下?作为通配符,因此必须跳过,因此答案应为 10(从 0 开始)。
我不知道如何更改上面的 linq 表达式中的代码才能做到这一点。
我尝试了 int index = str1.Zip(str2, (c1, c2) => c1 == c2 && c2!='?').TakeWhile(b => b).Count();
但这并没有改变任何事情,并且总是报告 6 而不是 9。
我想坚持使用 linq 而不是通过(更简单的)for 循环 谢谢
最佳答案
您需要通配符来算作一个额外的可能的 true
条件。因此,您需要使用 OR ||
而不是 AND &&
:
不是:
int index = str1.Zip(str2, (c1, c2) => c1 == c2 && c2 != '?').TakeWhile(b => b).Count();
相反:
int index = str1.Zip(str2, (c1, c2) => c1 == c2 || c2 == '?').TakeWhile(b => b).Count();
如果您还想忽略第一个输入中的通配符,您可以向表达式添加额外的 ||
。
关于C# Linq 如何比较两个字符串并报告第一个不同于 '?' 通配符的不同字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55828083/