比较两个C风格字符串的正确功能是什么?

Yok*_*hen 6 c c++ string compare

所以我陷入两难境地.我需要比较两个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)
Run Code Online (Sandbox Code Playgroud)

我认为第一个是地址,所以这个想法就出来了.第二个听起来对我来说是最好的选择,但无论如何我想听到反馈.其他三个让我一无所知.

tem*_*def 21

对于一般字符串比较,strcmp是适当的函数.您应该使用strncmp仅比较字符串中的某些字符数(例如,前缀),以及memcmp比较内存块.

也就是说,既然你正在使用C++,你应该完全避免这种情况并使用std::string类,它比C风格的字符串更容易使用并且通常更安全.std::string只需使用==运算符,就可以轻松地比较两个s的相等性.

希望这可以帮助!