Solidity: How to compare strings

Created on 29 Nov 2017  ·  5Comments  ·  Source: ethereum/solidity

How to compare strings in contract

All 5 comments

Please see https://solidity.readthedocs.io/en/develop/#language-documentation for guidance. Hint: ask on the appropriate channels, https://gitter.im/ethereum/soldity or https://ethereum.stackexchange.com

string name = "zhq";
function compareString(string _name) view public returns(string){
if(uint(keccak256(abi.encodePacked(name))) == uint(keccak256(abi.encodePacked(_name)))) {
return "对 ";
}else{
return "不对";
}
}

Reprinted sweetMegan's with formatting:

string name = "zhq";
function compareString(string _name) view public returns(string){
    if(uint(keccak256(abi.encodePacked(name))) == uint(keccak256(abi.encodePacked(_name)))) {
        return "对 ";
    }else{
        return "不对";
    }
}

I got the same question , could anyone help me out ?

@Chhe-chinyong Please have a look at the documentation: https://solidity.readthedocs.io/en/latest/types.html#bytes-and-strings-as-arrays. You can compare strings like this: keccak256(abi.encodePacked(s1)) == keccak256(abi.encodePacked(s2))

Was this page helpful?
0 / 5 - 0 ratings