C++ Comparison of String Literals

前端 未结 8 560
夕颜
夕颜 2020-11-27 06:01

I\'m a c++ newbie (just oldschool c). My son asked for help with this and I\'m unable to explain it. If he had asked me \"how do I compare strings\" I would have told hi

相关标签:
8条回答
  • 2020-11-27 06:17

    In the statement:

    cout << ("A"< "Z");
    

    You have created 2 string literals: "A" and "Z". These are of type const char * which is a pointer to a null terminated array of characters. The comparison here is comparing the pointers and not the values that they point to. It's this comparing of memory addresses here which is what gives you the compiler warning. The result of the comparison is going to be determined by where the compiler allocated the memory to which is going to be somewhat arbitrary from compiler to compiler. In this case it looks like the first literal found is getting assigned the first memory address by your compiler.

    Just like in C to compare these string literals properly you need to use strcmp which will do a value comparison.

    However when you do something the more idiomatic c++ way by doing:

    cout << (std::string("A") < std::string("Z"));
    

    Then you get the proper comparison of the values as that comparison operator is defined for std::string.

    0 讨论(0)
  • 2020-11-27 06:26

    A String is representing a pointer to memory area. So you at first compare only memory addresses with such code

    "Z"< "A"
    

    comparing strings is done with functions. They depend on "what kind of string" you have. You have char array strings, but they mid also be objects. These objects have other comparision functions. For instance the CString in MFC has the Compare but also the CompareNoCase function.

    For your strings you best use the strcmp. If you debug and step in you see what the function does: it compares every char of both strings and return an integer if the first difference occurs or zero if the same.

    int result = strcmp("Z", "A");
    

    Here you find some further sample code

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