对于 std::string 的 compare 和 == 之间的差异

好听的

在使用==std::string::compare在两个字符串之间使用时,我得到了不同的结果

这是我正在执行的代码。

#include <iostream>
#include <string>

int main()
{
    std::string str1 = "W";
    char tmpChar = 'W';
    std::string str2(1, tmpChar);
    
    bool equalCompare = str1.compare(str2);
    bool equalSign = (str1 == str2);
    std::cout << "Compare result: " << equalCompare << std::endl;
    std::cout << "Equal sign result: " << equalSign << std::endl;
    
    return 0;
}

我想这与我的创建方式有关str2,但这是我发现将单个字符转换为字符串的方式。

埃罗里卡

对于 std::string 的 compare 和 == 之间的差异

不同之处在于它们返回的内容。==当字符串比较相等时返回真,否则返回假。参数之前compare返回负整数*this,字符串相等时返回零,参数之前返回正整数*this

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章