在Solidity中是无法直接判断字符串相等的,可以通过哈希值是否相等来判断。
参考
//以字符串的哈希值来判断是否相等
function isEqual(string memory a, string memory b) public view returns (bool) {
//return a == b;
// hash(a) == hash(b) ==> a == b?
bytes32 hashA = keccak256(abi.encode(a));
bytes32 hashB = keccak256(abi.encode(b));
return hashA == hashB;
}
//eg 但是计算哈希值很费时,可以在这之前先判断下bytes是否相等
function compareStr (string _str1, string _str2) public returns(bool) {
if(bytes(_str1).length == bytes(_str2).length){
if(keccak256(abi.encodePacked(_str1)) == keccak256(abi.encodePacked(_str2))) {
return true;
}
}
return false;
}