blockchain - solidity 类型转换:int to string, 字符串连接 string concat

访问量: 321

refer to : https://stackoverflow.com/questions/47129173/how-to-convert-uint-to-string-in-solidity

solidity 默认不支持对字符串做处理。

解决办法:

int to string:

solidity ^0.8.0

import "@openzeppelin/contracts/utils/Strings.sol";

Strings.toString(myUINT)

拼接:(可以一次性拼接好多个 小字符串)

https://dev.to/hannudaniel/concatenate-two-strings-on-the-blockchain-using-solidity-smart-contracts-new-feature-in-v0812-549g

// <= 0.8.11
string(abi.encodePacked(text,added_text));   // 可以一次性传入多个参数
// > 0.8.11  
string.concat(text,added_text);   // 同上

完整例子:

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

import "@openzeppelin/contracts/utils/Strings.sol";

contract VeryGoodNftWithMoreClearMessage is ERC721URIStorage {

  uint256 private _currentId = 0;
  address public rootAddress = address(0);
  uint256 public _maxSupply = 3;

  event Minted(address to, uint256 nftId, address minter);

  modifier shouldLessThanMaxSupply(){

    // 在这里进行 int 与 string的转换, 字符串的拼接
    string memory message = string(abi.encodePacked("Reached max supply:(_maxSupply: ", Strings.toString(_maxSupply), ", _currentId: ", Strings.toString(_currentId), "), no available nft left" ));
    require( _currentId < _maxSupply, message);
    _;
  }

  constructor() ERC721("VeryGoodNftWithMoreClearMessage", "VGN") {
    rootAddress = msg.sender;
  }

  function mint(address to) external shouldLessThanMaxSupply{
    uint256 nftId = _currentId + 1;
    _mint(to, nftId);
    _currentId = nftId;
    address from = msg.sender;
    emit Minted(to, nftId, from);
  }
}

订阅/RSS Feed

Subscribe