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

前端 未结 2 2005
北海茫月
北海茫月 2020-12-02 00:56

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          


        
相关标签:
2条回答
  • 2020-12-02 01:01

    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!

    0 讨论(0)
  • 2020-12-02 01:11

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

    0 讨论(0)
提交回复
热议问题