如何比较两个char []数组的等效性?

时间:2013-05-11 14:05:54

标签: c# arrays compare

现在,我有两个char数组,foo1[]foo2[]。当我将它们转换为字符串并输出到控制台时,它们同时显示为bar。我知道我可以这样做:

int g;
for (int i=0;i<length.foo1;i++) {      // loop from 0 to length of array
    if (foo1[i]=foo2[i]) {             // if foo1[0] and foo2[0] are the same char
    g++;                               // increment a counter by 1
}
else                                   // otherwise...
{
    i=100;                             // set i to something that will halt the loop
}
if (g = length.foo1) {                 // if the incremented counter = length of array
    return true;                       // arrays are equal, since g only increments
}                                      // in the case of a match, g can ONLY equal the
else {                                 // array length if ALL chars match
    return false;                      // and if not true, false.

逐个字母地比较它们,但我猜这是一种更简单的方法。有趣的是,我为comparing char[] for eqivalency c#和类似关键字所做的大部分谷歌搜索都会导致大量有关比较STRING数组的信息,或者当数组的某些部分与某些内容匹配时比较字符串或字符数组...我已经...无法找到任何关于测试char数组的简单方法。踩过每个阵列是最好的方法吗?或者有没有办法比较foo1 = foo2或foo1 == foo2?这些都不适合我。

基本上,我需要测试char foo1[]char foo2[]是否{B,A,R}

5 个答案:

答案 0 :(得分:14)

您可能正在寻找:

foo2.SequenceEqual(foo1)

答案 1 :(得分:3)

我认为您可以使用SequenceEquals来比较数组,即使首先检查两个长度都有更好的性能。

答案 2 :(得分:1)

string s = new string(foo1);
string t = new string(foo2);

int c = string.Compare(s, t);
if(c==0){
    //its equal
}

答案 3 :(得分:1)

foo1.ToList().Intersect(foo2.ToList())

答案 4 :(得分:0)

您可以创建自己的函数,然后再将char []转换为字符串,然后比较两个字符串,该函数会更快。 1.首先比较数组的长度(如果不相等),则返回false。 2.开始遍历并比较每个字符,如果发现任何差异,则返回false,否则在循环返回true之后。

if(foo1.Length != foo2.Length){ return false;}
for(int i=0;i<foo1.Length;i++){
   if(foo1[i] != foo2[i]){ return false;}
}
return true;
相关问题