【问题标题】:How to compare strings in an "if" statement? [duplicate]如何比较“if”语句中的字符串? [复制]
【发布时间】:2011-11-22 05:41:21
【问题描述】:

我想测试一下“char”类型的变量是否可以与“cheese”之类的常规字符串进行比较,例如:

#include <stdio.h>

int main()
{
    char favoriteDairyProduct[30];

    scanf("%s",favoriteDairyProduct);

    if(favoriteDairyProduct == "cheese")
    {
        printf("You like cheese too!");
    }
    else
    {
        printf("I like cheese more.");
    }

    return 0;
}

(我实际上想要做的比这要长得多,但这是我坚持的主要部分。) 那么如何比较 C 中的两个字符串呢?

【问题讨论】:

  • 顺便说一句,像这样使用 scanf() 是一个非常严重的错误。如果您输入的单词超过 30 个字符,您的程序可能会崩溃。 fgets() 更安全。

标签: c string


【解决方案1】:

您正在寻找函数 strcmp 或来自 string.hstrncmp

由于字符串只是数组,你需要比较每个字符,所以这个函数会为你做这件事:

if (strcmp(favoriteDairyProduct, "cheese") == 0)
{
    printf("You like cheese too!");
}
else
{
    printf("I like cheese more.");
}

延伸阅读:strcmp at cplusplus.com

【讨论】:

    【解决方案2】:
    if(strcmp(aString, bString) == 0){
        //strings are the same
    }
    

    神速

    【讨论】:

      【解决方案3】:

      看看函数strcmpstrncmp

      【讨论】:

        【解决方案4】:

        您不能使用== 运算符比较字符数组。您必须使用字符串比较函数。看看Strings (c-faq)

        标准库的strcmp 函数比较两个字符串,如果它们相同,则返回 0,如果第一个字符串按字母顺序“小于”第二个字符串,则返回负数,如果第一个字符串是“,则返回正数”更大。”

        【讨论】:

          【解决方案5】:
          if(!strcmp(favoriteDairyProduct, "cheese"))
          {
              printf("You like cheese too!");
          }
          else
          {
              printf("I like cheese more.");
          }
          

          【讨论】:

          • 这里与接受的答案有什么不同?
          • @zar 简单的区别,但区别否定而不是 ==0。
          猜你喜欢
          • 1970-01-01
          • 2016-07-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-12-06
          • 1970-01-01
          • 2018-10-15
          相关资源
          最近更新 更多