How to compare strings in Solidity?


Trying to compare strings in Solidity using equality operators (==, ===) and it’s failing? That’s because strings are represented as dynamically-sized arrays of bytes, and the compiler does not understand how to compare these variable lengths.

Instead, we’d need to convert the string into something that the compiler knows how to deal with using these two functions: keccak256 and abi.encodePacked. First, we encode the strings to make sure the input is the correct type for keccak256. Then, the hashing function (keccak256) converts it into what == understands.

We’d need to encode them like so:

pragma solidity ^0.8.17;

contract StringCompare {
    function compareStrings(string memory a, string memory b) public pure returns (bool) {
        return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
    }
}

Now let’s make this a little more gas-efficient. What if we know that the string length input will be variable? We are going through 2 conversions twice, so this function does 4 operations before making the comparison. Why not invalidate the equality using length before running the expensive hashing algorithm? Here is what we can do:

pragma solidity ^0.8.17;

contract StringCompare {
    function compareStrings(string memory a, string memory b) public pure returns (bool) {
        if (bytes(a).length != bytes(b).length) { return false; }
        return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
    }
}

Don’t forget to check out Solidity docs on String Literals. Happy coding!