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

How do you compare strings in Solidity?

我假设比较字符串就像做一样简单:

function withStrs(string memory a, string memory b) internal {
  if (a == b) {
    // do something
  }
}

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

正确的方法是什么?

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

if (keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b))) {
  // do something
}

keccak256 是一个散列函数 supported by Solidity, and abi.encodePacked() encodes values via the Application Binary Interface