如何比较C字符串和C ++字符串?

Mis*_*ire 3 c++ string c-strings

我想找出为什么比较功能没有给我正确的结果?

据我所知,如果两个字符串相同,则应该返回0!

bool validatePassword(char id[], string password) {

    // cannot be the same as the id string
    if(password.compare(id) == 0) {
        cout << "password can not be as same as id\n";
        return false;
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

Geo*_*pis 5

正如Matteo Italia在另一个答案的评论中提到的那样。像这样使用std :: string的operator ==:

bool validatePassword(char id[], string password) {
    return password == id;
}
Run Code Online (Sandbox Code Playgroud)

此函数实际上是不必要的,因为您的呼叫者应该直接调用operator ==。


小智 1

您可以通过将 id 转换为字符串并与字符串进行比较来实现:

string idStr(id);
if (password == idStr){

}
Run Code Online (Sandbox Code Playgroud)

或者使用 strcmp 比较两个 char 数组:

if(strcmp (password.c_str(), id) == 0){

}
Run Code Online (Sandbox Code Playgroud)

您必须使用方法 c_str() 将字符串转换为字符数组

  • 仅仅为了进行比较而构造一个新字符串是浪费的,而且两种方法都不必要地复杂,因为 std::string 已经提供了 `operator==` 的重载来将 `std::string` 与 C 字符串进行比较。 (2认同)
  • 随意生活在构建 std::string 是免费的幻想世界中(事实并非如此;最近我不得不修复一个一直使用 `substr` 的解析器,不必要地敲击分配器;它变得快了 5 倍)。另外,就无缘无故地使用 C 结构而言,我同意,这就是我批评 strcmp 方法的原因。但这里的要点是,这两种解决方案都无缘无故地复杂,因为 `std::string` 可以简单地使用 `==` 与 C 字符串进行比较。 (2认同)