简体   繁体   English

如何检查值是否与字符串匹配

[英]How do I check if a value matches a string

I have a struct here with something like:我在这里有一个结构,类似于:

char *sname;
........
players[i].sname

equalling "James".相当于“詹姆斯”。

I need to check for equality between values like so:我需要像这样检查值之间的相等性:

if (players[i].sname == 'Lee')

but am not having much luck.但我运气不佳。 Is there a str* function I should be using or is there anyway to fix up my if statement?是否有我应该使用的str*函数,或者是否可以修复我的if语句?

The short answer: strcmp() .简短的回答: strcmp()

The long answer: So you've got this:长答案:所以你有这个:

if(players[i].sname == 'Lee')

This is wrong in several respects.这在几个方面都是错误的。 First, single-quotes mean "character literal" not "string literal" in C.首先,单引号在 C 中表示“字符文字”而不是“字符串文字”。

Secondly, and more importantly, "string1" == "string2" doesn't compare strings, it compares char * s, or pointers to characters.其次,更重要的是, "string1" == "string2"不比较字符串,它比较char * s,或指向字符的指针。 It will tell you if two strings are stored in the same memory location .它会告诉您两个字符串是否存储在同一个内存位置 That would mean they're equal, but a false result wouldn't mean they're inequal .这意味着它们是平等的,但错误的结果并不意味着它们是不平等的

strcmp() will basically go through and compare each character in the strings, stopping at the first character that isn't equal, and returning the difference between the two characters (which is why you have to say strcmp() == 0 or !strcmp() for equality). strcmp()基本上会遍历并比较字符串中的每个字符,在第一个不相等的字符处停止,并返回两个字符之间的差异(这就是为什么你必须说strcmp() == 0!strcmp()表示相等)。

Note also the functions strncmp() and memcmp() , which are similar to strcmp() but are safer.还要注意函数strncmp()memcmp() ,它们类似于strcmp()但更安全。

You should be using strcmp() :您应该使用strcmp()

if (strcmp(players[i].sname, "Lee") == 0) { ...

Also note that strings in C are surrounded by double quotes: "" .另请注意,C 中的字符串用双引号括起来: "" Single characters are surrounded by single quotes: '' .单个字符用单引号括起来: '' I'm not sure exactly what your compiler might be doing with 'Lee' , but it's almost certainly not what you want.我不确定您的编译器可能会对'Lee'做什么,但这几乎肯定不是您想要的。

You'd be looking for strcmp() from the header <string.h> .您会从头文件<string.h>寻找strcmp()

Note that you need a string — 'Lee' is not a string but a multi-character constant, which is allowed but seldom useful, not least because the representation is defined by the compiler, not the C standard.请注意,您需要一个字符串 — 'Lee'不是字符串而是一个多字符常量,这是允许的但很少有用,尤其是因为表示是由编译器定义的,而不是 C 标准。

If you are looking to compare two strings — call the pointers to them first and second , then you write:如果你想比较两个字符串——调用指向它们的指针firstsecond ,然后你写:

if (strcmp(first, second) == 0)    // first equal to second
if (strcmp(first, second) <= 0)    // first less than or equal to second
if (strcmp(first, second) <  0)    // first less than second
if (strcmp(first, second) >= 0)    // first greater than or equal to second
if (strcmp(first, second) >  0)    // first greater than second
if (strcmp(first, second) != 0)    // first unequal to second

This, in my view, makes it clear what the comparison is and so the notation should be used.在我看来,这清楚地说明了比较是什么,因此应该使用符号。 Note that strcmp() may return any negative value to indicate 'less than' or any positive value to indicate 'greater than'.请注意, strcmp()可以返回任何负值来表示“小于”或任何正值来表示“大于”。

You will find people who prefer:你会找到喜欢的人:

if (strcmp(first, second))    // first unequal to second
if (!strcmp(first, second))   // first equal to second

IMO, they have the advantage of brevity but the disadvantage of being less clear than the explicit comparisons with zero. IMO,它们具有简洁的优点,但缺点是不如与零的显式比较清晰。 YMMV .天啊

Be cautious about using strncmp() instead of strcmp() , which was suggested in one answer.谨慎使用strncmp()而不是strcmp() ,这是在一个答案中建议的。 If you have:如果你有:

if (strncmp(first, "command", 7) == 0)

then if first contains "commander" , the match will be valid.那么如果first包含"commander" ,则匹配将有效。 If that's not what you want but you want to use strncmp() anyway, you would write:如果这不是你想要的,但无论如何你想使用strncmp() ,你会写:

if (strncmp(first, "command", sizeof("command")) == 0)

This will correctly reject "commander" .这将正确拒绝"commander"

strcmp works fine, provided one of the strings is null terminated. strcmp 工作正常,前提是其中一个字符串以空字符结尾。 If both are max length and identical, the comparison will walk off the end, and most likely give a false negative result for the equality test.如果两者都是最大长度且相同,则比较将结束,并且很可能会为相等性测试提供假阴性结果。 If one string is fixed inside of "" marks in the strcmp itself, that's not an issue, because we know it's null terminated.如果一个字符串被固定在 strcmp 本身的 "" 标记内,那不是问题,因为我们知道它是空终止的。

If we are comparing two string variables, and we don't know if they are max length or not (maximum length ones are not null terminated), then we need to use strncmp, and use sizeof on one of them to get the third parameter.如果我们正在比较两个字符串变量,并且我们不知道它们是否是最大长度(最大长度的不是空终止),那么我们需要使用 strncmp,并在其中之一上使用 sizeof 来获取第三个参数. This solves the problem, because the sizeof is aware of the maximum length.这解决了问题,因为 sizeof 知道最大长度。 Strcmp is 100% safe if one of the strings is a literal in double quotes.如果字符串之一是双引号中的文字,则 strcmp 是 100% 安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM