Solidity

運算符 += 與字元串記憶體和字節記憶體類型不兼容?

  • May 26, 2022

我怎樣才能添加,字元串(b

$$ i $$數字和阿爾法變數?

   bytes memory number;
   bytes memory alpha;

   function getNumAndAlpha() public pure external returns( bytes n, bytes a){

   string memory str = "1jfjw2j34jcnsj512jdn3";

   bytes memory b = bytes(str);

   for(uint i=0; i< b.length; i++){

       if (b[i] == "0"  b[i] == "1"b[i] == "2"  b[i] == "2"  b[i] == "4" || b[i] == "5") {

           number += string(b[i]\n);

       } else {

           alpha += string(b[i]\n);
       }
   }

返回(數字,阿爾法)}

這是您的程式碼的工作版本,它集中字節並將數字與字母分開(我假設您想在這裡做)。

希望能幫助到你。

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;


contract Contract {



   function getNumAndAlpha() public pure returns( string memory Number, string memory Alpha){

   bytes memory number;
   bytes memory alpha;
   string memory str = "1jfjw2j34jcnsj512jdn3";

   bytes memory b = bytes(str);

   for(uint i=0; i < b.length; i++){

       if (b[i] == "0" ||  b[i] == "1" || b[i] == "2" || b[i] == "3" || b[i] == "4" || b[i] == "5") {

           number = (abi.encodePacked(number,b[i]));

       } else {

          alpha = (abi.encodePacked(alpha,b[i]));
       }
   }

         return (string(number), string(alpha));

   }


} 

引用自:https://ethereum.stackexchange.com/questions/129005