Reputation: 7066
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}
Upvotes: 5
Views: 28652
Reputation: 540
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;
Upvotes: 0
Reputation: 14874
I think you can use the SequenceEquals to compare the arrays, even though checking both lengths at first has better performance.
Upvotes: 4
Reputation: 8652
string s = new string(foo1);
string t = new string(foo2);
int c = string.Compare(s, t);
if(c==0){
//its equal
}
Upvotes: -2