How to concat two string values in Solidity
Asked Answered
S

2

9

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));
    }
}
Sassenach answered 22/10, 2021 at 14:36 Comment(0)
T
9

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.

Taliesin answered 23/10, 2021 at 12:17 Comment(0)
D
4

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

Dearly answered 22/4, 2022 at 8:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.