Skip to content

String Types

Strings are actually Arrays, very similar to a bytes-array. If that sounds too complicated, let me break down some quirks for you that are somewhat unique to Solidity:

  1. Natively, there are no String manipulation functions.
  2. No even string comparison is natively possible
  3. There are libraries to work with Strings
  4. Strings are expensive to store and work with in Solidity (Gas costs, we talk about them later)
  5. As a rule of thumb: try to avoid storing Strings, use Events instead (more on that later as well!)

If you still want to use Strings, then let's do an example!

Example Smart Contract

Let's create the following example Smart Contract, store a String and retrieve it again:

// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.1;

contract StringExample {
    string public myString = 'hello world!';

    function setMyString(string memory _myString) public {
        myString = _myString;

Deploy the Smart Contract into the JavaScript VM and retrieve the String. It should output "hello world!", since it was initialized with this value:

Now we can overwrite the String with another String:

Write any String you want into the input box next to "setMyString" - for example "". Then hit the "myString" button again:

Later, in the Gas-Cost section, you will see how inefficient it is to use Strings. I will also introduce some better ways storing Strings in a trustable way with Events on the Blockchain.

Last update: April 17, 2021