Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 939
Evan Conrad Avatar asked Feb 03 '19 01:02

Evan Conrad


1 Answers

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.

like image 196
Evan Conrad Avatar answered Nov 16 '22 15:11

Evan Conrad