search

Home  >  Q&A  >  body text

c++ - strcmp和==的区别?

Example:

    char alpha;
    scanf("%c", &alpha);
    if (strcmp(&alpha, "c") == 0) //if (alpha == 'c')
    {
        printf("same");
    }
    else
    {
        printf("different");
    }

man page上的 description也没有讲具体

The strcmp() function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.

我谷歌了, 但只找到了http://stackoverflow.com/ques... , c 部分感觉不是很详细, 想在这里请教下大家这两者实现机制的区别与效率

怪我咯怪我咯2767 days ago653

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-17 15:26:40

    Strcmp is used to determine whether strings of type char* are equal. The char* string is actually the first address of the string.
    And == directly determines whether the left and right sides are equal. If == is used to determine char* strings, it is equivalent to comparing their first addresses. Of course, it cannot determine whether the values ​​of the strings are consistent.
    If it is std::string, because the == operator has been overloaded, you can directly use == for comparison.
    In addition, std::string has a const char* constructor. You can usually use string("abc") == "abc" because when matching the == operator of string, the following abc will undergo implicit type conversion. .

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 15:26:40

    Can I ask, how do you use == to compare two strings? Are there any code examples?

    reply
    0
  • Cancelreply