比较两个C风格字符串的正确函数是什么

What is the proper function for comparing two C-style strings?

本文关键字:字符串 是什么 函数 风格 两个 比较      更新时间:2023-10-16

所以我陷入了进退两难的境地。我需要比较两个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的相等性。

希望这能有所帮助!

memcmpstrcmp都可以正常工作。要使用前者,您需要提前知道较短字符串的长度。