Simple way to concatenate strings in Solidity
Published
Update from April 2022
In version 0.8.12, Solidity included a string concat()
method that makes it even easier to concatenate strings. Here is how to use it:
string memory str_1 = 'hello ';
string memory str_2 = "world";
string memory result = string.concat(a, b);
// result will be "hello world"
For versions of Solidity previous to 0.8.12 you can still use the method below.
Concatenating strings is something very common and that you'll probably have to do sooner than later in your smart contracts. In other languages we can concatenate strings easily with operators like +
(in JavaScript) or .
(in PHP), but in Solidity, things are a little different.
Find below some examples:
string memory str_1 = 'hello ';
string memory str_2 = "world";
string memory result = string(abi.encodePacked(a, b));
// result will be "hello world"
string memory result_2 = string(abi.encodePacked(result, ", I'm working with strings"));
// result_2 will be "hello world, I'm working with strings"
In summary, to contatenate strings in solidity you have to use abi.encodePacked
with all the strings we want to contatenate as parameters, and cast the result as a string
.
TAGS