Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solidity long string constants over multiple lines

Just wondering if there is a way to split long strings over more than one line in solidity? I can't find any kind of line continuation character, and compile error is thrown if you try to use two lines like this. Concatenating strings appears to be complex as well

 string memory s = "This is a very long line of text which I would like to split over
 several lines";

Concatenating strings appears to be complex as well. Do I just have to put the very long string on a very long line?

like image 228
GGizmos Avatar asked Oct 25 '25 09:10

GGizmos


1 Answers

You can split the value to multiple separate string literals, each on one line.

pragma solidity ^0.8;

contract MyContract {
    string s = "This is a very "
        "long line of text "
        "which I would like to split "
        "over several lines";
}

Docs: https://docs.soliditylang.org/en/v0.8.6/types.html#string-literals-and-types


If you want to concatenate multiple strings, you can use the abi.encodePacked() method returning bytes array, and then cast the bytes back to string.

pragma solidity ^0.8;

contract MyContract {
    string s1 = "Lorem";
    string s2 = "ipsum";
    
    function foo() external view returns (string memory) {
        return string(abi.encodePacked(s1, " ", s2));
    }
}

Edit: Since v0.8.12, you can also use string.concat() (that was not available in previous versions).

pragma solidity ^0.8.12;

contract MyContract {
    string s1 = "Lorem";
    string s2 = "ipsum";

    function foo() external view returns (string memory) {
        return string.concat(s1, " ", s2);
    }
}

Docs: https://docs.soliditylang.org/en/v0.8.12/types.html#the-functions-bytes-concat-and-string-concat

like image 147
Petr Hejda Avatar answered Oct 28 '25 02:10

Petr Hejda