代码之家  ›  专栏  ›  技术社区  ›  Dannark

如何在C中比较两个以上的字符串?

  •  2
  • Dannark  · 技术社区  · 12 年前

    我知道有strcmp,但它只是让我比较两个字符串,我需要比较很多字符串

    这个不起作用:

    if(strcmp (resposta, "S" || "s" || "N" || "n")== 0)
            printf("Resposta = S");
        else
            printf("Resposta != S");
    
        printf("\nfim");
    
    5 回复  |  直到 12 年前
        1
  •  4
  •   CennoxX    4 年前

    由于表达式 "S" || "s" || "N" || "n" "S" 因为短路。

    您必须逐一将其与候选字符串进行比较:

    if (strcmp(resposta, "S") == 0
        || strcmp(resposta, "s") == 0
        || strcmp(resposta, "N") == 0
        || strcmp(resposta, "n") == 0)
    {
        printf("Resposta = S");
    }
    
        2
  •  2
  •   bitfiddler    12 年前
    if( strcmp (resposta, "S") == 0 || strcmp (resposta,"s") == 0  || strcmp (resposta,"N") == 0 || strcmp (resposta, "n") == 0)
    
        3
  •  1
  •   ajay    12 年前

    标准库函数的签名 strcmp 是-

    int strcmp(const char *s1, const char *s2);
    

    然而,您将其称为

    strcmp(resposta, "S" || "s" || "N" || "n")
    

    第二个参数的值为1,其类型为 int ,因为字符串文本的计算结果是指向其第一个字符的指针 NULL 。这显然是错误的。 你应该用

    if(!((strcmp(resposta, "S") && strcmp(resposta, "N") && strcmp(resposta, "n")))
        printf("Resposta = S");
    else
        printf("Resposta != S");
    
        4
  •  1
  •   Arkku    12 年前

    如果有很多字符串要比较,可以使用它们创建一个数组并对其进行迭代 NULL (因此 while 条件工程):

    const char *strings[] = { "S", "Sim", "N", "NAO", NULL };
                                                  // ^ add more strings here
    const char **s = strings;
    while (*s) {
        if (strcmp(resposta, *s) == 0) {
            (void) printf("Matched: %s\n", *s);
            break; // stop searching when a match is found (the matching string is *s)
        }
        ++s;
    }
    if (!*s) {
        (void) printf("Didn't match anything\n");
    }
    

    如果要匹配大量字符串,最好的方法是对字符串数组进行排序并在其中进行二进制搜索。

        5
  •  1
  •   EOF    12 年前

    如果您要查找的字符串只有一个 char ,可以使用 switch 陈述

    switch(*string) //will compare the first character of your string
    {
        case('s'):
        {
            //whatever you do
            break;
        }
        case('S'):
        {
            //whatever else
            break;
        }
        ... //other characters
        default:
        {
            //error handling on incorrect input
            break;
        }
    }
    

    编辑:如果您正在比较不同长度的字符串(即您正在查找字符串中的前缀),请注意 strcmp() 从不 认为他们是平等的。

    如果需要查找前缀,则需要 strncmp() (注意n),每个字符串和字符串长度分别对应。