[Solidity] How to concatenate strings?

This section explains how to concatenate strings in Solidity.

Syntax

To concatenate strings in Solidity, do the following.

string(abi.encodePacked(string1, string2 [, ...[, stringN]]))

Sample Code

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract Test {

    function strConcat(string memory str1, string memory str2) public pure returns(string memory) {
        // concatenate strings
        return string(abi.encodePacked(str1, str2));
    }

}

Since EVM (Ethereum Virtual Machine) cannot directly handle strings, the string manipulation in Solidity requires the use of abi.encodePacked() to encode ABI to convert the string to a form that EVM can handle.

タイトルとURLをコピーしました