什么是比较两个C风格字符串应有的功能? [英] What is the proper function for comparing two C-style strings?
问题描述
所以我有一个两难选择。我需要比较两个C风格的字符串和我搜索的结果将是最appropiate的功能:
So I have a dilemma. I need to compare two C-style strings and I searched for the functions that would be the most appropiate:
memcmp //Compare two blocks of memory (function)
strcmp //Compare two strings (function )
strcoll //Compare two strings using locale (function)
strncmp //Compare characters of two strings (function)
strxfrm //Transform string using locale (function)
第一个我认为是地址,这样的想法是出来。
第二个听起来就像是最好的选择我,但我想听到的反馈反正。
其他三个离开我无言以对。
The first one I think is for addresses, so the idea is out. The second one sounds like the best choice to me, but I wanna hear feedback anyway. The other three leave me clueless.
推荐答案
对于一般的字符串比较, STRCMP
是相应的功能。您应该使用 STRNCMP
只能从字符串比较字符的一定数目(例如,preFIX)和 memcmp
来比较的内存块。
For general string comparisons, strcmp
is the appropriate function. You should use strncmp
to only compare some number of characters from a string (for example, a prefix), and memcmp
to compare blocks of memory.
这是说,因为你正在使用C ++,你应该完全避免这一点,并使用的std ::字符串
类,这是非常容易使用,一般比更安全C风格的字符串。您可以通过只使用轻松地比较两个
运营商。的std ::字符串
S代表平等==
That said, since you're using C++, you should avoid this altogether and use the std::string
class, which is much easier to use and generally safer than C-style strings. You can compare two std::string
s for equality easily by just using the ==
operator.
希望这有助于!
这篇关于什么是比较两个C风格字符串应有的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!