C语言 在 C 中使用相等运算符 == 比较两个字符串的相等性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3933614/
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-09-02 06:42:17  来源:igfitidea点击:

Using the equality operator == to compare two strings for equality in C

cstringpointersequalityequality-operator

提问by Carlo del Mundo

int main (int argc, **argv)
{
       if (argv[1] == "-hello")
            printf("True\n");
       else
            printf("False\n");
}
# ./myProg -hello
False

Why? I realize strcmp(argv[1], "-hello") == 0returns true... but why can't I use the equality operator to compare two C strings?

为什么?我意识到strcmp(argv[1], "-hello") == 0返回 true...但为什么我不能使用相等运算符来比较两个 C 字符串?

回答by Oliver Charlesworth

Because argv[1](for instance) is actually a pointer to the string. So all you're doing is comparing pointers.

因为argv[1](例如)实际上是一个指向字符串的指针。所以你所做的就是比较指针。

回答by Bart van Ingen Schenau

You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.

您不能将 C 中的字符串与 == 进行比较,因为 C 编译器并没有真正了解字符串文字以外的字符串。

The compiler sees a comparison with a char*on either side, so it does a pointer comparison (which compares the addresses stored in the pointers)

编译器char*在任一侧看到与 a 的比较,因此它进行指针比较(比较存储在指针中的地址)

回答by pmg

In Cbecause, in most contexts, an array "decays into a pointer to its first element".

C因为,在大多数情况下,阵列“衰变为一个指向它的第一个元素”。

So, when you have the array "foobar"and use it in most contexts, it decays into a pointer:

因此,当您拥有数组"foobar"并在大多数情况下使用它时,它会衰减为一个指针:

if (name == "foobar") /* ... */; /* comparing name with a pointer */

What you want it to compare the contents of the arraywith something. You can do that manually

你想让它把数组内容something进行比较。您可以手动执行此操作

if ('p' == *("foobar")) /* ... */; /* false: 'p' != 'f' */
if ('m' == *("foobar"+1)) /* ... */; /* false: 'm' != 'o' */
if ('g' == *("foobar"+2)) /* ... */; /* false: 'g' != 'o' */

or automatically

或自动

if (strcmp(name, "foobar")) /* name is not "foobar" */;

回答by jv42

Because there is no such thing as a C string.

因为没有 C 字符串这样的东西。

In C, a string is usually an array of char, or a pointer to char (which is nearly the same). Comparing a pointer/array to a const array won't give the expected results.

在 C 中,字符串通常是一个 char 数组,或一个指向 char 的指针(几乎相同)。将指针/数组与 const 数组进行比较不会给出预期的结果。

UPDATE: what I meant by 'no C string' is, there is no string in C. What's usually referred to as a 'C string' is language independent (as 'Pascal string' is), it's the representation of strings as a null-terminated linear array of characters.

更新:我所说的“无 C 字符串”的意思是,C 中没有字符串。通常所说的“C 字符串”是独立于语言的(如“Pascal 字符串”),它是字符串的表示为 null - 终止的线性字符数组。

回答by John Bode

In C, string values (including string literals) are represented as arrays of charfollowed by a 0 terminator, and you cannot use the ==operator to compare array contents; the language simply doesn't define the operation.

在 C 中,字符串值(包括字符串文字)表示为char后跟 0 终止==符的数组,并且您不能使用运算符来比较数组内容;该语言根本没有定义操作。

Except when it is the operand of either the sizeofor &operators, or when it is a string literal being used to initialize another array in a declaration, an expression with type "N-element array of T" will have its type implicitly converted (decay) to type "pointer to T", and the value of the expression will be the address of the first element of the array.

除非它是sizeofor&运算符的操作数,或者当它是用于在声明中初始化另一个数组的字符串文字时,类型为“T 的 N 元素数组”的表达式将隐式转换其类型(衰减)键入“指向 T 的指针”,表达式的值将是数组第一个元素的地址。

So when you write

所以当你写

if (argv[1] == "-hello")

the compiler implicitly converts the expression "-hello"from type "7-element array of char" to "pointer to char" (argv[1]is already a pointer type), and the value of the expression is the addressof the character '-'. So what ==winds up comparing are two pointervalues, which are (most likely) never going to be equal since "-hello"and argv[1](most likely) occupy different regions in memory.

编译器隐式地将表达式"-hello"从类型“char的7元素数组”转换为“指向char的指针”(argv[1]已经是指针类型),表达式的值为字符的地址'-'。所以==最终比较的是两个指针值,它们(很可能)永远不会相等,因为"-hello"并且argv[1](很可能)占据内存中的不同区域。

This is why you have to use library functions like strcmp()to compare string values.

这就是为什么你必须使用库函数strcmp()来比较字符串值。

回答by Tom

Because C strings dont exist as such. They are char arrays ending in a \0.

因为 C 字符串不存在。它们是以 a 结尾的字符数组\0

The equality operator ==will test that the pointer to the first element of the array are the same. It wont compare lexicographically.

相等运算符==将测试指向数组第一个元素的指针是否相同。它不会按字典顺序进行比较。

On the other hand "-hello" == "-hello"mayreturn non zero, but that doesn't mean that the ==operator compares lexicographycally. That's due to other facts.

另一方面,"-hello" == "-hello"可能返回非零,但这并不意味着==运算符按字典顺序进行比较。这是由于其他事实。

If you want to compare lexicographycally, you can always

如果你想按字典顺序比较,你总是可以

#define STR_EQ(s1,s2)    \
   strcmp(s1,s2) == 0

Reading harder I see that you tagged as c++. So you could

仔细阅读,我发现您标记为 c++。所以你可以

 std::string arg1 ( argv[1] );

 if (arg1 == "-hello"){
    // yeahh!!!
 }
 else{
    //awwwww
 }

回答by kanaka

Strings are not native types in C. What you are comparing in that example are two pointers. One to your first argument, and the other is a static character array with the contents of "-hello".

字符串不是 C 中的本机类型。您在该示例中比较的是两个指针。一个是您的第一个参数,另一个是包含“-hello”内容的静态字符数组。

You really want to use strncmp or something similar.

你真的想使用 strncmp 或类似的东西。

回答by waffle paradox

When you're using ==, you're comparing pointers. That is, it will return true if the two operands refer to the same string in memory. Therefore, it's unsuitable for use in comparing strings lexicographically.

当您使用 == 时,您是在比较指针。也就是说,如果两个操作数引用内存中的同一个字符串,它将返回 true。因此,它不适合用于按字典顺序比较字符串。

回答by Anthony

Because C strings are array of characters. Arrays are simply pointers to the first element in the array, and when you compare two pointers using == it compares the memory address they point to, not the values that they point to.

因为 C 字符串是字符数组。数组只是指向数组中第一个元素的指针,当您使用 == 比较两个指针时,它比较它们指向的内存地址,而不是它们指向的值。