4

Right now, I have two char arrays, foo1[] and foo2[]. When I convert them to string and output to the console, they BOTH appear as bar. I know that I can do something like this:

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.

to compare them letter by letter, but I'm guessing there's an easier way. Interestingly, most of the googling I do for comparing char[] for eqivalency c# and similar keywords results in a whole mess of info about comparing STRING arrays, or comparing string or char arrays when PART of the array matches something or another...I've not been able to find anything about easy ways of testing char arrays as being equal. Is stepping through each array the best way? or is there some way to compare if foo1=foo2 or foo1==foo2? Neither of those worked for me.

Basically, I need to test if char foo1[] and char foo2[] are BOTH {B,A,R}

4

5 回答 5

18

您可能正在寻找:

foo2.SequenceEqual(foo1)
于 2013-05-11T14:50:35.460 回答
3

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

于 2013-05-11T14:55:39.873 回答
1
foo1.ToList().Intersect(foo2.ToList())
于 2013-05-11T14:43:54.257 回答
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;
于 2018-09-04T10:27:09.283 回答
-1
string s = new string(foo1);
string t = new string(foo2);

int c = string.Compare(s, t);
if(c==0){
    //its equal
}
于 2013-05-11T14:10:54.583 回答