我想比较两个char数组,我想要(如果它们不相等)输出上要显示的不同char。例如,在我的下面的代码中,不同的char是" y"。所以在输出上,我想要写:"不同的char是y,它在数组中而不是在ar"中。我正在使用C#,这是我写的代码,我得到了CompareTo方法的错误。谁能帮我 ?提前致谢。 NB,我还是初学者。
char[] ar = { 'a', 'h', 'm', 'a', 'd' };
char[] ay = { 'a', 'y', 'm', 'a', 'd' };
if (ar.SequenceEqual(ay))
{
Console.WriteLine("Success");
}
else
{
Console.WriteLine("failure");
char diff = ar.CompareTo((Object)ay));
Console.Write(diff);
}
答案 0 :(得分:2)
看看这个;
n
答案 1 :(得分:0)
尝试这个选项,我还为数组添加了一个额外的字符,用于故障检查:
using System;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
char[] ar = { 'a', 'h', 'm', 'a', 'd' };
char[] ay = { 'a', 'y', 'f', 'm', 'a', 'd' };
Console.WriteLine(GetDiffOfCharArray(ay, ar, "ay", "ar"));
ay = new char[] { 'a', 'h', 'm', 'a', 'd' };
Console.WriteLine(GetDiffOfCharArray(ay, ar, "ay", "ar"));
Console.ReadLine();
}
private static string GetDiffOfCharArray(char[] array1Values, char[] array2Values, string array1Name, string array2Name)
{
string result = "";
if (array1Values.SequenceEqual(array2Values))
{
result = string.Format("Success, Array '{0}' matches Array '{1}'", array1Name, array2Name);
}
else
{
var diff = array1Values.Except(array2Values);
result = string.Format("Failure, the different char is '{0}', it is in the array '{1}' but not in the array '{2}'",
string.Join("','", diff),
array1Name,
array1Name);
}
return result;
}
}
}
失败和成功的输出如下:
失败,不同的字符是'y','f',它在数组'ay'中但不在数组'ay
中成功,数组'ay'匹配数组'ar'
答案 2 :(得分:0)
使用Except方法可以实现这一点非常简单,而且您不必两次比较数组。
char[] ar = { 'a', 'h', 'm', 'a', 'd' };
char[] ay = { 'a', 'y', 'm', 'a', 'd' };
var different = ar.Except(ay).ToList();
if (different.Count == 0)
{
Console.WriteLine("Success");
}
else
{
foreach (char c in different)
{
Console.WriteLine(c);
}
}
Console.WriteLine("Percent of similarity: "+(100-different.Count*100/ar.Length) +"%");
答案 3 :(得分:0)
IEnumerable<char> inArArray = ar.Except(ay);
foreach (char c in inArArray) {
Console.WriteLine("{0} Exists in ar but not in ay",c);
}
IEnumerable<char> inAyrray = ay.Except(ar);
foreach (char c in inAyrray)
{
Console.WriteLine("{0} Exists in ay but not in ar", c);
}