为什么直接比较字符串失败,但是使用char *成功 [英] Why directly comparing string fails, but succeeds using char*

查看:85
本文介绍了为什么直接比较字符串失败,但是使用char *成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下工作代码中;如果我直接使用比较

In the following working code; instead of using *tofind, if I directly use the comparison

if(*argv[i] == "and")

失败.

为什么会这样?

/**
* Find index of the word "and"
* ./a.out alice and bob
*/
int main(int argc, char **argv) {
    int i = 0;
    char *tofind = "and";
    while (argv[i] != NULL) {
        if(*argv[i] == *tofind) {
            printf("%d\n", i + 1);
            break;
        }
        ++i;
    }
    return 0;
}

推荐答案

if(*argv[i] == "and")不应该编译,我想您的意思是if (argv[i] == "and"),它将比较两者的指针,而不是字符串内容.

if(*argv[i] == "and") shouldn't compile, I think you mean if (argv[i] == "and"), that would compare the pointers of the two, not the string content.

if (*argv[i] == *tofind)也不符合您的预期,它仅比较第一个字符.

if (*argv[i] == *tofind) doesn't work as you expected either, it only compares the first character.

要比较字符串,请使用strcmp():

To compare strings, use strcmp():

if (strcmp(argv[i], tofind) == 0)

这篇关于为什么直接比较字符串失败,但是使用char *成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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