C - 与 if 语句相关的 strcmp

C - strcmp related to an if statement

在下面的代码中,我使用 strcmp 比较两个字符串,并将此比较作为 if 语句的条件。 使用下面的代码,输出将为 hello world,因为字符串 "one" 等于字符串 "two".

#include <stdio.h>
#include <string.h>

char one[4] = "abc";
char two[4] = "abc";

int main() {

    if (strcmp(one, two) == 0) {
        printf("hello world\n");
    }
}

现在我想更改程序,如果两个字符串不同则打印 hello world 所以我更改程序:

#include <stdio.h>
#include <string.h>

char one[4] = "abc";
char two[4] = "xyz";

int main() {

    if (strcmp(one, two) == 1) {
        printf("hello world\n");
    }
}

我不明白为什么它不打印任何东西。

您误解了 strcmp 的工作原理。要测试字符串是否不同,请使用

if(strcmp(one, two))

因为 strcmp() 在这种情况下 return 是一个负整数。

所以改变这个:

if (strcmp(one, two) == 1) {

对此:

if (strcmp(one, two) != 0) {

考虑字符串不同的所有情况。

请注意,您可以通过阅读 ref 或打印函数 return 的内容自己发现这一点,如下所示:

printf("%d\n", strcmp(one, two));
// prints -23

strcmp returns 当两个字符串相等时为零,当它们不同时它 returns 不是零,所以你需要改变你的 if in你的代码是这样的

if ( strcmp(one, two) != 0 ) {
    printf("hello world\n");
}

根据C标准(7.23.4.2 strcmp函数)

3 The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2.

所以你需要的是像

这样写if语句
if ( strcmp(one, two) != 0 ) {

if ( !( strcmp(one, two) == 0 ) ) {

正确的行为是:

if (strcmp(one, two) != 0) {
    printf("hello world\n");
}

实际上,这个函数 returns 两个字符串之间的 差异

  • < 0: 第一个不匹配的字符在 ptr1 中的值小于 ptr2 中的值。
  • 0:两个字符串的内容相等
  • > 0:第一个不匹配的字符在 ptr1 中的值大于 ptr2 中的值。

This is an example of how strcmp could be implemented