如何比较两个char []数组的等效性? [英] How do I Compare two char[] arrays for equivalency?

查看:93
本文介绍了如何比较两个char []数组的等效性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

逐个字母地比较它们,但我想有一种更简单的方法.有趣的是,我对comparing char[] for eqivalency c#和类似关键字所做的大多数谷歌搜索都会导致一整堆信息混乱,其中涉及比较STRING数组,或者当数组的PART匹配某些东西时比较字符串或char数组.能够找到有关测试char数组是否相等的简便方法的任何信息.遍历每个数组是最好的方法吗?还是有某种方法可以比较foo1 = foo2或foo1 == foo2?这些都不对我有用.

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.

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

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

推荐答案

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

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

这篇关于如何比较两个char []数组的等效性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆