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

时间:2014-03-23 15:58:21

标签: c string strcmp

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

这个不起作用:

if(strcmp (resposta, "S" || "s" || "N" || "n")== 0)
        printf("Resposta = S");
    else
        printf("Resposta != S");

    printf("\nfim");

5 个答案:

答案 0 :(得分: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");
}

答案 1 :(得分:2)

if( strcmp (resposta, "S") == 0 || strcmp (resposta,"s") == 0  || strcmp (resposta,"N") == 0 || strcmp (resposta, "n") == 0)

答案 2 :(得分:1)

如果您要查找的字符串只有一个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)每个字符串和字符串长度。

答案 3 :(得分:1)

标准库函数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)

如果你有很多要比较的字符串,你可以用它们制作一个数组并迭代它。在此示例中,数组以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");
}

如果你有很多要匹配的字符串,那么更好的方法是对字符串数组进行排序并在其中进行二进制搜索。

相关问题