How do I Compare two char[] arrays for equivalency?

醉酒当歌 提交于 2019-12-01 07:05:04

问题


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}


回答1:


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

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



回答2:


You are possibly looking for:

foo2.SequenceEqual(foo1)



回答3:


I think you can use the SequenceEquals to compare the arrays, even though checking both lengths at first has better performance.




回答4:


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



回答5:


you can make a function of yours which will be faster then first converting char[] to string then compare two strings. 1. First compare length of the arrays if they are not equal return false. 2. start looping through and compare each char, If you find any diff return false else after the loop return 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;


来源:https://stackoverflow.com/questions/16497898/how-do-i-compare-two-char-arrays-for-equivalency

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!