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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With