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

2022-01-25 00:00:00 string c compare c++

所以我进退两难了.我需要比较两个 C 风格的字符串,然后搜索最合适的函数:

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 仅比较字符串中的一些字符(例如,前缀),并使用 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::string 类,它比 C 风格的字符串更易于使用且通常更安全.您只需使用 == 运算符即可轻松比较两个 std::string 的相等性.

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::strings for equality easily by just using the == operator.

希望这会有所帮助!

相关文章