Compare Strings in Solidity

Published by Mario Oettler on

Last Updated on 12. June 2023 by Mario Oettler

Solidity’s string operations are very limited. This also affects comparing strings. The necessary steps to compare two strings are:

  1. abi-encode both strings seperately:

bytes res1 = abi.encodePacked(<my_string_1>);

bytes res2 = abi.encodePacked(<my_string_2>);

  • Create a keccak hash for each encoded result:

hash1 = keccak256(res1);

hash2 = keccak256(res2)

  • Compare both hashes with

hash1 == hash2;

Example for comparing Strings in Solidity

This is a fully working example of how to compare two strings in Solidity:

pragma solidity 0.8.20;
contract CompareStrings{
    function compareStrings(string memory _s1, string memory _s2) public pure returns(bool areEual){
        return keccak256(abi.encodePacked(_s1)) == keccak256(abi.encodePacked(_s2));
    }
}
Categories:

https://blockchain-academy.hs-mittweida.de/wp-content/uploads/2021/04/logo_bcam_rgb_gross.png

Welcome

Blockchain Academy

Continue with credential

No account yet?

Powered by Hidy

Register with Hidy


Register
Sign in

We need the following credential to register:

please select:

To create a new account, we need the following data from you:

We would appreciate the following additional information from you for the creation of your account:

Welcome

Blockchain Academy

Continue with credential

Already have an account?

Powered by Hidy

Sign in with Hidy


Register
Sign in

We need the following credential to log in:

please select: