你如何比较 Solidity 中的字符串?

Eva*_*rad 5 ethereum solidity

我认为比较字符串会像做一样简单:

function withStrs(string memory a, string memory b) internal {
  if (a == b) {
    // do something
  }
}
Run Code Online (Sandbox Code Playgroud)

但是这样做会给我一个错误Operator == not compatible with types string memory and string memory

什么是正确的方法?

Eva*_*rad 10

您可以通过散列字符串的打包编码值来比较字符串:

if (keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b))) {
  // do something
}
Run Code Online (Sandbox Code Playgroud)

keccak256Solidity 支持的散列函数,并abi.encodePacked()通过应用程序二进制接口对值进行编码。

  • 可能简单地转换为字节(来自[另一个答案](https://ethereum.stackexchange.com/questions/4559/operator-not-known-with-type-string-storage-ref-and-literal-string#comment88932_11754) ) 就 Gas 而言比 `abi.encodePacked` 更便宜。我们必须检查一下。 (2认同)