fbpx

How to manipulate strings in Solidity?

Julien Klepatch

Manipulating strings in Solidity is notoriously difficult. This is surprising for most developers who are used to manipulating easily in other programming languages like Javascript or Python.

In this article I give a couple of useful code snippets to do some simple string manipulations in Solidity.

Warning: Keep in mind that manipulating strings in Solidity is costly in gas. If you can avoid it and use other types like bytes and bytes32, that’s better.

Get length of a string in Solidity

function length(string calldata str) external pure returns(uint) {
        return bytes(str).length;
    }

Concatenate 2 strings in Solidity

function concatenate(
        string calldata a,
        string calldata b)
        external 
        pure
        returns(string memory) {
            return string(abi.encodePacked(a, b));
        }

Compare 2 strings in Solidity

function compare(
    string calldata a,
    string calldata b)
    external
    pure
    returns(bool) {
        return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
    }

Reverse 2 strings in Solidity

function reverse(string calldata _str) external pure returns(string memory) {
        bytes memory str = bytes(_str);
        string memory tmp = new string(str.length);
        bytes memory _reverse = bytes(tmp);

        for(uint i = 0; i < str.length; i++) {
            _reverse[str.length - i - 1] = str[i];
        }
        return string(_reverse);
    }

Bonus Stringutils libary

If you want to do even more string manipulations you can use the Stringutils library. Warning: This wasn't updated for the last 2 years and is not compatible with Solidity 0.6.

0 Comments

Leave a Reply

More great articles

How to create NFT on OpenSea For Beginners (no coding)



In this article I will show you how to create an NFT on Ethereum.

 We will use OpenSea, The biggest…

Read Story

Overview of the Github repos of Truffle

You probably have heard or used Truffle, the leading framework for Solidity smart contracts. But are you aware of all…

Read Story
Polymarket founder Shayne Coplan

The Blockchain developer behind Polymarket meteoric success

Let's dive into the fascinating story of the founder of Polymarket. His name is Shayne Coplan, he is Blockchain developer,…

Read Story

Never miss a minute

Get great content to your inbox every week. No spam.
[contact-form-7 id="6" title="Footer CTA Subscribe Form"]
Arrow-up