溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

solidity智能合約[11]-字符串

發(fā)布時間:2020-06-17 18:57:03 來源:網(wǎng)絡(luò) 閱讀:697 作者:jonson_jackson 欄目:開發(fā)技術(shù)

字符串

string 類型存儲字符串, 在solidity中使用了UTF-8格式來存儲字符串。

1
2
3
string public name="jonson";//6a6f6e736f6e
string public name1="!@#$%^&*())*";
string public name2="我愛你";

字符串不能直接的獲取長度和內(nèi)容

下面是錯誤的方式

1
2
3
4
5
6
7
// function getLength() returns(uint){
//     name.length;
// }

// function getName() returns(bytes1) {
//     return name[0];
// }

獲取字符串長度和內(nèi)容和的正確方式

1
2
3
4
5
6
7
 function getLength() public view returns(uint){
   return bytes(name).length;
}

function getName() public view returns(bytes1){
return bytes(name)[1];
}

修改字符串中的內(nèi)容

1
2
3
4
function changeName() public{
// bytes(name)[0]=0x55;
   bytes(name)[0]='P';
}

證明中文占了3個字節(jié)

1
2
3
4
   string public name2="我愛你";
  function getLength3() public view returns(uint){
   return bytes(name2).length;
}

字符串轉(zhuǎn)動態(tài)字節(jié)數(shù)組

1
2
3
4
function  getBytes() public view returns(bytes){

   return bytes(name);
}

完整代碼測試

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
pragma solidity ^0.4.23;

contract StringTest{

   string public name="jonson";//6a6f6e736f6e
   string public name1="!@#$%^&*())*";
   string public name2="我愛你";

   // function getLength() returns(uint){
   //     name.length;
   // }
     function getLength() public view returns(uint){
       return bytes(name).length;
   }
   // function getName() returns(bytes1) {
   //     return name[0];
   // }
        function getName() public view returns(bytes1){
       return bytes(name)[1];
   }

   function changeName() public{
   // bytes(name)[0]=0x55;
       bytes(name)[0]='P';
   }

   function  getBytes() public view returns(bytes){

       return bytes(name);
   }

        function getLength2() public view returns(uint){
       return bytes(name1).length;
   }
   function  getBytes1() public view returns(bytes){

       return bytes(name1);
   }

   function getLength3() public view returns(uint){
       return bytes(name2).length;
   }
   function  getBytes2() public view returns(bytes){

       return bytes(name2);
   }
}

總結(jié)

1、字符串是特殊的動態(tài)長度字節(jié)數(shù)組
2、字符串不能夠字節(jié)的修改長度和內(nèi)容,需要轉(zhuǎn)換為bytes動態(tài)字節(jié)數(shù)組
3、字符串在solidity中使用了UTF8格式來存儲,所以漢字占了3個字節(jié),英文和特殊字符占了一個字節(jié)

  • 本文鏈接: https://dreamerjonson.com/2018/11/15/solidity-11/

  • 版權(quán)聲明: 本博客所有文章除特別聲明外,均采用 CC BY 4.0 CN協(xié)議 許可協(xié)議。轉(zhuǎn)載請注明出處!

solidity智能合約[11]-字符串

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI