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
Compare part of an input string using strcmp() in C
提问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/。

