compare strings in solidity

2018-04-16 14:54:06

I wrote a function that takes two strings as arguments and compares them and returns bool value. Here is the code.

function compareStringsbyBytes(string s1, string s2) public pure returns(bool)

{

bytes memory s1bytes = bytes(s1);

bytes memory s2bytes = bytes(s2);

if(s1bytes.length!=s2bytes.length) {

return false;

}

else{

for(uint i = 0;i

{

if(s1bytes[i] != s2bytes[i])

return false;

}

return true;

}

}

The contract deployment failed in this case with transaction out of gas error. Can someone help me understand the problem with this code?

Thanks!!

@henkiedoodle's comment is correct, it would be much simpler and easier to compare hashes of the strings.

You are unable to directly compare strings, (ie return(s1 == s1) will give the error

TypeError: Operator == not compatible with types string memory and string memory), but if the strings are identical then so will their hashes be.

The full function could the

  • @henkiedoodle's comment is correct, it would be much simpler and easier to compare hashes of the strings.

    You are unable to directly compare strings, (ie return(s1 == s1) will give the error

    TypeError: Operator == not compatible with types string memory and string memory), but if the strings are identical then so will their hashes be.

    The full function could then be simplified to

    function compareStringsbyBytes(string s1, string s2) public pure returns(bool){

    return keccak256(s1) == keccak256(s2);

    }

    However, in future if you receive the out of gas error, you may also want to try increasing the gas limit of your transaction.

    2018-04-16 15:51:44
  • When the contract deployment fails, you should be looking for other issues:

    The contract does not compile under your version of solc (depends on tools used), meaning you are trying to deploy an empty bytecode.

    Something in the constructor does not work, e.g. a require() condition is not met.

    The deployment cost is beyond your unlocked account's balance or it is over the amount of gas supplied (you may have to increase if the estimate is incorrect), or it is over the chain's block gasLimit.

    It's unlikely the failure to deploy the contract has anything to do with the design of this function since it is not involved in deployment itself. As an aside, I would upvote the hash comparison idea on grounds of readability and simplicity.

    Hope it helps.

    2018-04-16 17:14:41