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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With