'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));
}
}
Solution 1:[1]
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.
Solution 2:[2]
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);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | cameel |
Solution 2 |