Compare with other programming language, string comparison cannot be done with ==
or !=
in Solidity. It is because Solidity do not support operator natively. To doing so, it needs workaround.
We need to hash string to byte array to compare value in Solidity. Sample code as below.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: GPL-3.0 | |
pragma solidity >=0.7.1 <0.9.0; | |
contract IsEqualStringContract { | |
function equals(string memory a, string memory b) public pure returns (bool) { | |
if(bytes(a).length != bytes(b).length) { | |
return false; | |
} else { | |
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b)); | |
} | |
} | |
} |
When execute, result as below.
Leave a Reply