strcmp or string::compare?

后端 未结 6 2158
北荒
北荒 2020-12-03 11:28

I want to compare two strings. Is it possible with strcmp? (I tried and it does not seem to work). Is string::compare a solution?

Other tha

相关标签:
6条回答
  • 2020-12-03 12:10

    Assuming you mean std::string, why not use the overloaded operators: str1 == str2, str1 < str2?

    0 讨论(0)
  • 2020-12-03 12:13

    See std::basic_string::compare and std::basic_string operators reference (in particular, there exists operator==, operator!=, operator<, etc.). What else do you need?

    0 讨论(0)
  • 2020-12-03 12:15

    When using C++ use C++ functions viz. string::compare. When using C and you are forced to use char* for string, use strcmp

    0 讨论(0)
  • 2020-12-03 12:20

    std::string can contain (and compare!) embedded null characters.

    are*comp(...) will compare c-style strings, comparing up to the first null character (or the specified max nr of bytes/characters)

    string::compare is actually implemented as a template basic_string so you can expect it to work for other types such as wstring

    On the unclear phrase to "compare a string to a char" you can compare the char to *string.begin() or lookup the first occurrence (string::find_first_of and string::find_first_not_of)

    Disclaimer: typed on my HTC, typos reserved :)

    0 讨论(0)
  • 2020-12-03 12:23

    By your question, "is there a way to compare a string to a char?" do you mean "How do I find out if a particular char is contained in a string?" If so, the the C-library function:

      char *strchr(const char *s, int c);
    

    will do it for you.

    -- pete

    0 讨论(0)
  • 2020-12-03 12:31

    For C++, use std::string and compare using string::compare.

    For C use strcmp. If your (i meant your programs) strings (for some weird reason) aren't nul terminated, use strncmp instead.

    But why would someone not use something as simple as == for std::string ?

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