solidity 中的字符串拼接


如果都是字符串格式的拼接,使用
string(abi.encodePacked(tokenHost, _type))
如果 tokenHost 或者 _type 不是字符串格式,拼接可能会出错:
invalid codepoint at offset 31; unexpected continuation byte
遇到这种情况,就需要将里面的两项先转换成bytes 格式,再拼接
在这里给出自己用到的一些函数:
address 转换为string
function addressToString(address _addr) public pure returns(string) {
    bytes32 value = bytes32(uint256(_addr));
    bytes memory alphabet = "0123456789abcdef";

    bytes memory str = new bytes(51);
    str[0] = "0";
    str[1] = "x";
    for (uint i = 0; i < 20; i++) {
                            str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))];
    str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))];
    }
    return string(str);
}
但是在高版本soldity(本人用户 0.8.4)中,这个方法可能有兼容性问题,无法,无法直接将 address 转为 uint256,如果有用 0.8.X的,可以用下面这个
function addressToString(address _addr) public pure returns(string memory) {
    bytes32 value = bytes32(uint256(uint160(address(_addr))));

    bytes memory alphabet = "0123456789abcdef";

    bytes memory str = new bytes(51);
    str[0] = "0";
    str[1] = "x";
    for (uint i = 0; i < 20; i++) {
        str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))];
        str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))];
    }
    return string(str);
}
uint 转换为 string
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
    if (_i == 0) {
        return "0";
    }
    uint j = _i;
    uint len;
    while (j != 0) {
        len++;
        j /= 10;
    }
    bytes memory bstr = new bytes(len);
    uint k = len;
    while (_i != 0) {
        k = k-1;
        uint8 temp = (48 + uint8(_i - _i / 10 * 10));
        bytes1 b1 = bytes1(temp);
        bstr[k] = b1;
        _i /= 10;
    }
    return string(bstr);
}