How do you compare strings in Solidity?
Asked Answered
C

1

16

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?

Cluff answered 3/2, 2019 at 1:23 Comment(0)
C
37

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.

Cluff answered 3/2, 2019 at 1:23 Comment(1)
Probably simple conversion to bytes (from another answer) is cheaper in terms of gas than abi.encodePacked. We have to check.Hydropic

© 2022 - 2024 — McMap. All rights reserved.