比较两个C风格字符串的正确function是什么?
所以我陷入两难境地。 我需要比较两个C风格的字符串,我搜索了最合适的函数:
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)
我认为第一个是地址,所以这个想法就出来了。 第二个听起来对我来说是最好的选择,但无论如何我想听到反馈。 其他三个让我无能为力。
对于一般字符串比较, strcmp
是适当的函数。 您应该使用strncmp
仅比较字符串中的一些字符数(例如,前缀)和memcmp
来比较内存块。
也就是说,既然你正在使用C ++,你应该完全避免这种情况并使用std::string
类,它比C风格的字符串更容易使用并且通常更安全。 只需使用==
运算符,就可以轻松地比较两个std::string
s的相等性。
希望这可以帮助!
memcmp
和strcmp
都可以正常工作。 要使用前者,您需要提前知道较短字符串的长度。