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

发布时间:2020-06-17 18:57:03 作者:jonson_jackson
来源:网络 阅读:681

字符串

string 类型存储字符串, 在solidity中使用了UTF-8格式来存储字符串。

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

字符串不能直接的获取长度和内容

下面是错误的方式

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

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

获取字符串长度和内容和的正确方式

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];
}

修改字符串中的内容

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

证明中文占了3个字节

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

字符串转动态字节数组

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);
   }
}

总结

1、字符串是特殊的动态长度字节数组
2、字符串不能够字节的修改长度和内容,需要转换为bytes动态字节数组
3、字符串在solidity中使用了UTF8格式来存储,所以汉字占了3个字节,英文和特殊字符占了一个字节

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

推荐阅读:
  1. 学习区块链有什么用处
  2. 区块链的特性有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

区块链 solidity 智能合约

上一篇:msdp 排错思路

下一篇:Python-面向对象编程

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》