DEV Community

Cover image for Concatenate Two Strings on the Blockchain using Solidity Smart Contracts (NEW FEATURE IN v0.8.12)
Hannu-Daniel Goiss
Hannu-Daniel Goiss

Posted on

Concatenate Two Strings on the Blockchain using Solidity Smart Contracts (NEW FEATURE IN v0.8.12)

Some sources claim it is not possible to concatenate strings in Solidity Smart Contracts on the Blockchain. (string.concat is supported from Solidity v0.8.12)
Keep in mind, that Solidity is still in the early stages (despite being 2022, we are at version v0.8.12). This is a fast-evolving space, hence changes will be made.
My previous post ( https://dev.to/hannudaniel/deploying-a-smart-contract-on-the-tron-blockchain-48e1 ) mentions it is not possible to concatenate two Strings on the TRON Blockchain. This turns out to be correct, as TRON IDE (in Feb 2022) uses Solidity v0.8.6. The official documentation for Solidity v0.8.6 ( https://docs.soliditylang.org/en/v0.8.6/types.html#value-types ) also makes a reference to string.concat not being available and suggests alternatives.

All of the Google Search results give advice either that it's not possible or that you have to use encodePacked to combine two Strings:

According to the official documentation, string.concat is supported from v0.8.12. Check out: https://docs.soliditylang.org/en/v0.8.12/types.html#value-types

Let's take a look at some samples:
DON'T DO IT LIKE THIS!

contract Poem {
    string public text;

    function addLine(string memory added_text) public {
        text = text + added_text;
    }
}
Enter fullscreen mode Exit fullscreen mode

This would be a way to concatenate Strings using abi.encodePacked (using Solidity v0.8.11 or older):

contract Poem {
    string public text;

    function addLine(string memory added_text) public {
        text = string(abi.encodePacked(text,added_text));
    }
}
Enter fullscreen mode Exit fullscreen mode

You can now use the string.concate function (using Solidity v0.8.12 or newer):

contract Poem {
    string public text;

    function addLine(string memory added_text) public {
           text = string.concat(text,added_text);
    }
}
Enter fullscreen mode Exit fullscreen mode

Concatenating two Strings directly on the Blockchain is now possible. But should it be done? It might be better to execute expensive transactions outside of the Blockchain.

Discussion (0)