[Solidity] How to handle long strings (multi-line strings)?

This section explains how to handle long strings (multi-line strings) in Solidity.

Syntax

There are two main ways to handle long strings (multi-line strings) in Solidity.

One is to simply use quotation marks as line breaks, and the other is to use string concatenation.

Use quotation marks as line breaks

A new line is inserted after each quotation as follows.

"string 1"
"string 2"
[ ...[stringN]];

Use string concatenation

Concatenates strings with string(abi.encodePacked()) and breaks this argument string.

string(
    abi.encodePacked(
        "string 1",
        "string 2",
        [, ...[, stringN]]
    )
);

Sample Code

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract Test {

    function showMultilineString() public pure returns(string memory) {
        // Use quotation marks as line breaks
        string memory str =
            "This "
            "is "
            "multiline "
            "string."
            ;
        return str;
    }

    function showMultilineStringByAbi() public pure returns(string memory) {
        // Use string concatenation
        string memory str = 
            string(
                abi.encodePacked(
                    "This ",
                    "is ",
                    "multiline ",
                    "string ",
                    "by ",
                    "abi."
                )
            );
        return str;
    }

}

The former way of breaking quotation marks is simpler. Take a quick look at the latter method as well to review how to do string concatenation.

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