如何在 Solidity 中连接两个字符串值

MD *_*MIA 9 blockchain ethereum solidity

连接两个或多个字符串值 -

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));
    }
}
Run Code Online (Sandbox Code Playgroud)

cam*_*eel 8

编辑:正如 @MAMY S\xc3\xa9bastien 在另一个答案中提到的,从 Solidity 0.8.12 开始,你终于可以使用string.concat()这个:

\n
string.concat(a, "-", b);\n
Run Code Online (Sandbox Code Playgroud)\n
\n

旧答案:

\n

这是目前执行此操作的规范方法:

\n
string(bytes.concat(bytes(a), "-", bytes(b)));\n
Run Code Online (Sandbox Code Playgroud)\n

你的例子仍然有效并且很好。bytes.concat()被添加是因为abi.encodePacked()可能会被弃用,以支持在未来某个时候拥有更具体的功能。bytes目前,在散列之前连接数组似乎是其主要用例。

\n

bytes.concat()这些转换使for的使用string有点冗长,这就是为什么string.concat()将在未来的版本中引入的原因。

\n