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:
- https://www.youtube.com/watch?v=gNlwpr3vGYM
- https://ethereum.stackexchange.com/questions/729/how-to-concatenate-strings-in-solidity
- https://ethereum.stackexchange.com/questions/64385/how-to-concatenate-string-array-into-a-single-string
- https://blog.finxter.com/string-concatenation-in-solidity/
- https://betterprogramming.pub/solidity-playing-with-strings-aca62d118ae5
- https://eattheblocks.com/how-to-manipulate-strings-in-solidity/
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;
}
}
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));
}
}
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);
}
}
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.
Top comments (0)