1 C++判断两个字符串是否相等

1.1 直接比较

#include <iostream>
#include <string>

int main()
{
    std::string a = "a";
    std::string b = "a";

    if (a == b)
    {
        std::cout << "两个字符串相等" << std::endl;
    }
    else
    {
        std::cout << "两个字符串不相等" << std::endl;
    }

    return 0;
}

1.2 使用C函数strcmp比较

#include <iostream>
#include <string>

int main()
{
    std::string a = "a";
    std::string b = "a";

    if(strcmp(a.c_str(),b.c_str()) == 0)
    {
        std::cout << "两个字符串相等" << std::endl;
    }
    else
    {
        std::cout << "两个字符串不相等" << std::endl;
    }

    return 0;
}

1.3 使用std::string的工具成员函数compare比较

#include <iostream>
#include <string>

int main()
{
    std::string a = "a";
    std::string b = "a";

    if (a.compare(b) == 0)
    {
        std::cout << "两个字符串相等" << std::endl;
    }
    else
    {
        std::cout << "两个字符串不相等" << std::endl;
    }

    return 0;
}