Compare Strings in Solidity
Solidity’s string operations are very limited. This also affects comparing strings. The necessary steps to compare two strings are:
- 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));
}
}