Strings

Everyone's Favorite Type

Having seen dynamic types in action (via dynamic arrays), it is time that we look at the type that has been absent from our discussion of the Solidity programming language: strings. Like most other programming languages, Solidity allows us to write literal text via strings, which have no size restriction.

As with most programming languages, strings in Solidity are an array of characters (represented by a byte); below is the syntax to declaring a string:

string M stringName;

where M is the location of the string; below are the following locations where a string can be defined:

  • memory: within the body of a function and as a function parameter

  • calldata: as a function parameter

Below is a code snippet which uses strings extensively:

contract StringExample {

    string name = "John";
    
    function getName() public view returns(string memory) {
        return name;
    }
    
    function setName(string calldata _name) public {
        name = _name;
    }

}

Last updated