温馨提示×

温馨提示×

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

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

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

发布时间:2020-06-17 18:57:03 阅读:721 作者:jonson_jackson 栏目:开发技术

字符串

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

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

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

下面是错误的方式

1234567
// function getLength() returns(uint){ //     name.length; // } // function getName() returns(bytes1) { //     return name[0]; // }

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

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

修改字符串中的内容

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

证明中文占了3个字节

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

字符串转动态字节数组

1234
function  getBytes() public view returns(bytes){    return bytes(name);}

完整代码测试

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
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个字节,英文和特殊字符占了一个字节

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

  • 版权声明: 本博客所有文章除特别声明外,均采用 CC BY 4.0 CN协议 许可协议。转载请注明出处!

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

向AI问一下细节

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

AI