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