[Ethereum] How to concatenate strings in solidity


I'm trying to concatenate two strings in solidity.

I tried with + or . but neither option works. There is not much documentation on string concatenation yet. Is it even possible?

If not, can I insert variables into strings?

Best Answer

As of Feb 2022, in Solidity v0.8.12 you can now concatenate strings in a simpler fashion!

string.concat(s1, s2)

Taken directly from the solidity docs on strings and bytes:

Solidity does not have string manipulation functions, but there are third-party string libraries. You can also compare two strings by their keccak256-hash using keccak256(abi.encodePacked(s1)) == keccak256(abi.encodePacked(s2)) and concatenate two strings using string.concat(s1, s2).

contract Poem {
    string public text;

    function addLine(string memory added_text) public {
           text = string.concat(text,added_text);

The above code snippet is provided by Hannu-Daniel Goiss on his article about string concatenation.

Related Topic