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

此生再无相见时 提交于 2019-11-26 14:46:50

问题


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.


回答1:


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.

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.

Hope this helps!




回答2:


Both memcmp and strcmp will work fine. To use the former, you'll need to know the length of the shorter string in advance.



来源:https://stackoverflow.com/questions/9122000/what-is-the-proper-function-for-comparing-two-c-style-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!