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

查看:22
本文介绍了如何比较两个 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 equivalency c# 和类似关键字所做的大部分搜索都会导致关于比较 STRING 数组或在数组的一部分匹配时比较字符串或 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天全站免登陆