String compare in solidity

dave123124dave123124 Posts: 10Member
I'm trying to compare an inputted string parameter with a string previously saved and getting compiler error:
ERROR Solidity: :64:6: Error: Operator == not compatible with types string memory and string storage pointer
Is there a simple way to compare strings?

Comments

  • chrisethchriseth Posts: 170Member ✭✭✭
    This has to be done manually for now:

    function stringsEqual(string storage _a, string memory _b) internal returns (bool) {
    bytes storage a = bytes(_a);
    bytes memory b = bytes(_b);
    if (a.length != b.length)
    return false;
    // @todo unroll this loop
    for (uint i = 0; i < a.length; i ++)
    if (a[i] != b[i])
    return false;
    return true;
    }
  • AjoyBhatiaAjoyBhatia Posts: 3Member
    I found that the following code works, too, even if either of the strings is from storage. Is there a disadvantage to coding it this way, e.g. does it use more gas, etc.? Or does it not matter? Just curious.
    function stringsEqual(string _a, string _b) internal returns (bool) {
    bytes memory a = bytes(_a);
    bytes memory b = bytes(_b);
    ...
Sign In or Register to comment.