小编Ale*_*der的帖子

在 Solidity 中是否有一种有效的方法将字符串数组连接成单个字符串?

我的目标是编写一个函数,它接受一个字符串数组,并返回一个包含所有输入字符串组合的字符串。

例如,在 Python 中可以这样完成:

result = ''.join(['hello', 'solidity', 'world'])  # hellosolidityworld
Run Code Online (Sandbox Code Playgroud)

我当前的实现似乎根本没有效率:

function concat(string[] memory words) internal pure returns (string memory) {
    // calculate output length
    uint256 bytesLength;
    for (uint256 i = 0; i < words.length; i++) {
        bytesLength += bytes(words[i]).length;
    }

    bytes memory output = new bytes(bytesLength);
    uint256 currentByte;

    for (uint256 i = 0; i < words.length; i++) {
        bytes memory bytesWord = bytes(words[i]);
        for (uint256 j = 0; j < bytesWord.length; j++) {
            output[currentByte] = bytesWord[j];
            currentByte++;
        } …
Run Code Online (Sandbox Code Playgroud)

solidity

1
推荐指数
1
解决办法
2444
查看次数

标签 统计

solidity ×1