15

I would assume comparing strings would be as easy as doing:

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

But doing so gives me an error Operator == not compatible with types string memory and string memory.

What's the right way?

Evan Conrad
  • 3,993
  • 4
  • 28
  • 46

1 Answers1

35

You can compare strings by hashing the packed encoding values of the string:

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

keccak256 is a hashing function supported by Solidity, and abi.encodePacked() encodes values via the Application Binary Interface.

Evan Conrad
  • 3,993
  • 4
  • 28
  • 46
  • 2
    Probably simple conversion to bytes (from [another answer](https://ethereum.stackexchange.com/questions/4559/operator-not-compatible-with-type-string-storage-ref-and-literal-string#comment88932_11754)) is cheaper in terms of gas than `abi.encodePacked`. We have to check. – Denis Untevskiy May 13 '22 at 08:05