我如何检查是否值的字符串相匹配 [英] How do I check if a value matches a string

查看:158
本文介绍了我如何检查是否值的字符串相匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

主要BRAINFREEZE而在这里学习C

Major brainfreeze while learning C here.

我在这里有一个结构的东西,如:

I have a struct here with something like:

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

等于詹姆斯。

我需要像这样的数值之间的检查平等:

I need to check for equality between values like so:

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

但我没有多少运气。有没有我应该使用或反正是有解决了我的if语句STR功能。它不是ATM工作。

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. It's not working atm.

推荐答案

答案很简单:的 的strcmp()

The short answer: strcmp().

长回答:所以,你有这样的:

The long answer: So you've got this:

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

这是错误的在几个方面。首先,单引号用C表示字符文字而不是字符串。

This is wrong in several respects. First, single-quotes mean "character literal" not "string literal" in C.

第二,更重要的是,字符串1==字符串2不比较字符串,它比较的char * S,或指针字符。它会告诉你,如果两个字符串的存储在相同的内存位置的。这将意味着他们是平等的,但错误的结果并不意味着他们的不相等

Secondly, and more importantly, "string1" == "string2" doesn't compare strings, it compares char *s, or pointers to characters. 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()将基本经历,并在字符串的每个字符比较,在不等于第一个字符停止和返回两个字符之间的差(这就是为什么你必须说的strcmp()== 0 !STRCMP()相等)。

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).

还要注意功能 STRNCMP() memcmp() ,这是类似的strcmp(),但比较安全。

Note also the functions strncmp() and memcmp(), which are similar to strcmp() but are safer.

这篇关于我如何检查是否值的字符串相匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆