EatTheBlocks Forum

How to compare strings in Solidity

Hello everyne,

I hope you are all well :slight_smile:

I have a problem with solidity coding.

I am trying to make a “require” with
require(newMessage == “hello”);

but the compilator of remix says that the operator == is not compatible with string memory and the literal_string “hello”.

For info here is my function:
function setMessage(string memory newMessage) public {
require(newMessage == “hello”);
message = newMessage;

Do you know if there is a way to write my require which would be accepted by the compilator?

Thank you in advance

Take care

Hi Pierre, I have re-written your question “How to compare strings in Solidity”.

Strings are very limited in solidity and you can’t directly compare them. However a trick is to hash the strings and compare the resulting bytes. In your case, the require statement would be:

require(keccak256(abi.encodePacked((newMessage))) == keccak256(abi.encodePacked(("hello"))));

Thank you so much :slight_smile:

1 Like