Back to homepage

Simple way to compare strings in Solidity


Comparing strings is something very common in programming languages but in Solidity we do it a little different.

Solidity doesn't have native string comparison, so if we try to use common operators we'll ran into some issues.

operator == not compatible with type string

If you try to compare strings using common operators like == or != you'll get an error message similar to these:

operator != not compatible with type string storage

This is because Solidity does not support those operators in string variables, but there is a simple workaround 😉

Compare string hashes with keccak256

Instead of using common operators == (or tripple equal as in JavaScript ===) or != , we can compare string values by comparing the strings keccak256 hashes to see if they match.

However, we can't directly pass strings to keccak256. Instead, we will pass abi.encodePacked() as an argument, passing to this one a specific string or a string variable.

See an example below 👇

function isSolidity(string memory _language) public {
  // Compare string keccak256 hashes to check equality
  if (keccak256(abi.encodePacked('Solidity')) == keccak256(abi.encodePacked(_language))) {
    // do something here...


If you enjoyed this article consider sharing it on social media or buying me a coffee ✌️

Buy Me A Coffee