比较 C 中 char[] 的相等性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2440420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:29:23  来源:igfitidea点击:

Compare equality of char[] in C

c++cequality

提问by rksprst

I have two variables:

我有两个变量:

char charTime[] = "TIME";
char buf[] = "SOMETHINGELSE";

I want to check if these two are equal... using charTime == bufdoesn't work.

我想检查这两个是否相等......使用charTime == buf不起作用。

What should I use, and can someone explain why using ==doesn't work?

我应该使用什么,有人可以解释为什么使用==不起作用?

Would this action be different in C and C++?

这个动作在 C 和 C++ 中会有所不同吗?

回答by Johannes Schaub - litb

char charTime[] = "TIME"; char buf[] = "SOMETHINGELSE";

C++and C(remove std::for C):

C++C(删除std::C):

bool equal = (std::strcmp(charTime, buf) == 0);

But the true C++ way:

但真正的 C++ 方式:

std::string charTime = "TIME", buf = "SOMETHINGELSE";
bool equal = (charTime == buf);

Using ==does not work because it tries to compare the addresses of the first character of each array (obviously, they do not equal). It won't compare the content of both arrays.

Using==不起作用,因为它试图比较每个数组的第一个字符的地址(显然,它们不相等)。它不会比较两个数组的内容。

回答by zellio

In c you could use the strcmp function from string.h, it returns 0 if they are equal

在 c 中,您可以使用 string.h 中的 strcmp 函数,如果它们相等则返回 0

#include <string.h>

if( !strcmp( charTime, buf ))

回答by CB Bailey

In an expression using ==the names of chararrays decay into char*pointing to the start of their respective arrays. The comparison is then perform in terms of the values of the pointers themselves and not the actual contents of the arrays.

在使用数组==名称的表达式中,会char衰减为char*指向各自数组的开头。然后根据指针本身的值而不是数组的实际内容执行比较。

==will only return true for two pointers pointing to the same location and false otherwise, even if they are pointing to two arrays with identical contents.

==只会对指向同一位置的两个指针返回 true,否则返回 false,即使它们指向具有相同内容的两个数组。

What you need is the standard library function strcmp. This expression evaluates as true if the arrays contain the same contents (up to the terminating null character which must be present in both arrays fro strcmpto work safely).

您需要的是标准库函数strcmp。如果数组包含相同的内容(直到两个数组中必须存在的终止空字符才能strcmp安全工作),则此表达式的计算结果为真。

strcmp(charTime, buf) == 0

回答by lajuette

You are checking the identity charTimeand buf. To check the equality, loop over each character in one array and compare them with the related character in the other array.

您正在检查身份charTimebuf。要检查相等性,请遍历一个数组中的每个字符,并将它们与另一个数组中的相关字符进行比较。

回答by lajuette

Check them in a for loop. Get the ASCII numbers for each char once they change they're not equal.

在 for 循环中检查它们。获取每个字符的 ASCII 数字,一旦它们改变它们不相等。