Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat two string values in Solidity

Concat two or more string values-

pragma solidity 0.8.9;

contract StringConcatation{
    function AppendString(string memory a, string memory b) public pure returns (string memory) {
        return string(abi.encodePacked(a,"-",b));
    }
}
like image 886
MD SHOHAG MIA Avatar asked May 17 '26 10:05

MD SHOHAG MIA


2 Answers

EDIT: As mentioned in another answer by @MAMY Sébastien, since Solidity 0.8.12 you can finally use string.concat() for this:

string.concat(a, "-", b);

Old answer:

This is the canonical way to do it currently:

string(bytes.concat(bytes(a), "-", bytes(b)));

Your example still works and is fine though. bytes.concat() was added because abi.encodePacked() might be deprecated in favor of having more specific functions at some point in the future. Concatenating bytes arrays before hashing seems to be its main use case for now.

The conversions make the use of bytes.concat() for string a bit verbose, which is why string.concat() is going to be introduced in future versions.

like image 62
cameel Avatar answered May 19 '26 02:05

cameel


From Solidity 0.8.12, you can use string.concat() to concatenate strings. Your code will look like:

pragma solidity 0.8.12;

contract StringConcatation {
    function AppendString(string memory a, string memory b) public pure returns (string memory) {
        return string.concat(a,"-",b);
    }
}

source: https://docs.soliditylang.org/en/latest/types.html?highlight=concat#the-functions-bytes-concat-and-string-concat

like image 28
Sébastien M. Avatar answered May 19 '26 03:05

Sébastien M.