Search code examples
ethereumsolidity

How do you compare strings in Solidity?


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?


Solution

  • 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.