C语言 在 C 中使用 strcmp() 比较输入字符串的一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13832321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:43:43  来源:igfitidea点击:

Compare part of an input string using strcmp() in C

cstrcmp

提问by user1872384

Normally strcmp is used with two arguments [e.g. strcmp(str1,"garden")], and it will return 0 if both are the same.

通常 strcmp 与两个参数一起使用 [例如 strcmp(str1,"garden")],如果两者相同,它将返回 0。

Is it possible to compare part of the input, say the first five character of the input? (for example, strcmp(str1,"garde",5))

是否可以比较输入的一部分,比如输入的前五个字符?(例如,strcmp(str1,"garde",5)

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

int main(void) {

    char str1[] = "garden";

    if (strcmp(str1, "garden") == 0)
    {
        printf("1");
    }
    if (strcmp(str1, "garden", 6) == 0)
    {
        printf("2");
    }
    if (strcmp(str1, "garde", 5) == 0)
    {
        printf("3");
    }
    return 0;
}

回答by goji

Use strncmp:

使用 strncmp:

if (strncmp(str, "test", 4) == 0) { printf("it matches!"); }

See http://www.cplusplus.com/reference/cstring/strncmp/for more info.

有关更多信息,请参阅http://www.cplusplus.com/reference/cstring/strncmp/

回答by Crozin

You're looking for strncmp().

您正在寻找strncmp().

Keep in mind that C does not supports overloading, so each "variation" of the same function has an unique name.

请记住,C 不支持重载,因此同一函数的每个“变体”都有唯一的名称。