Solidity Strings

whiteboard crypto logo
Published by:
Whiteboard Crypto
on

Strings are a reference-type variable in Solidity that hold characters and numbers in an array format. They are useful for holding text or longer messages. Here is an example of a contract that uses a string in Solidity:

//SPDX-License-Identifier: MIT
pragma solidity 0.8.13;

contract stringExample{

    string public name = "Tom";

    function changeName(string memory _newName) public{
        name = _newName;
    }

    function getName() public view returns(string memory){
        return name;
    }
}

Strings are actually dynamically-sized arrays that are encoded with the UTF-8 protocol. These can contain any ASCII character, as well as unicode literals like emojis if properly declared.

There are not many functions to use on a string, in fact you can’t even compare two strings easily, but there is a “concat” function that works well. This takes two strings and returns one string as if they were pushed together.

You can use single quotes or double quotes to represent a string. There are escape characters as well, which are listed below:

\”Double Quote
\’Single Quote
\nNew Line
\\Single Backslash
\tTab
\rReturn
\bBackspace

You can also cast numbers and bytes to strings by using the “string()” cast feature.

Comparing two strings

It is not possible to compare two strings with the current version of Solidity. If you try to do so, you will receive an error:

operator not compatible with types literal_string and bytes32 solution

Instead, you can hash the value of each item and compare the hashes together. Here is an example of comparing two strings using the keccak256 hashing function:

//SPDX-License-Identifier: MIT
pragma solidity 0.8.13;

contract stringExample{

    string public name = "Tom";

    function checkName(string memory _nameToCheck) public view returns (bool){
        if(keccak256(abi.encodePacked(name)) == keccak256(abi.encodePacked(_nameToCheck))){
            return true;
        }
        return false;
    }

}
whiteboard crypto logo

WhiteboardCrypto is the #1 online resource for crypto education that explains topics of the cryptocurrency world using analogies, stories, and examples so that anyone can easily understand them. Growing to over 870,000 Youtube subscribers, the content has been shared around the world, played in public conferences and universities, and even in Congress.