[Solidity] String comparison

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.

// 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.

About C.H. Ling 260 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.