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?

  • Optimized for low gas-consumption

    The ethereum community has implemented some ABI encoding functions which can be accessed natively without having to call another contract. This is how you could append a string to another with ABI encoding:

    function append(string a, string b, string c, string d, string e) internal pure returns (string) {
    
        return string(abi.encodePacked(a, b, c, d, e));
    
    }
    

    For demonstration, I called both functions, this one and the one used in the oraclizeAPI contract as proposed earlier, in remix with 5x the argument "string" and compared the gas consumption which turned out to be for ABI encoding less than 2/3 of what the other solution burns and the execution cost only about 1/7th:

    Initial Solution:
    Transaction cost: 45380
    Execution cost: 19436

    ABI encoding:
    Transaction cost: 28650
    Execution cost: 2706


    To be fair, ABI encoding has not been around for too long and the earlier proposed solutions get the job done as well. I have been using the strConcat function from oraclizeAPI for some time myself. However, especially if you need this function to be called by another smart contract or internally by a function changing the state of the contract, for the sake of cost-efficiency, you should definitely use ABI encoding.

    This is the correct answer in 2019

    What version of Solidity does this require? I got error: TypeError: Data location must be "storage" or "memory" for parameter in function, but none was given. function append(string a, string b, string c, string d, string e, string f) internal pure returns (string) {

    I think, back when I wrote the answer, I was still using Solidity ^0.4.24. In Solidity 0.5.0 and higher, you are required to specify for strings whether they will be stored in memory or storage. If you add the memory keyword after string for every parameter and the return value, everything should work as expected.

    As of Solidity 0.5.0, `abi.encodePacked` is the recommended way. I can confirm that it works when the more complicated old way hits the block gas limit with the same two strings being concatenated. https://solidity.readthedocs.io/en/v0.5.3/frequently-asked-questions.html#can-i-concatenate-two-strings

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM