【Solidity】学习(1)

string

string类型不可以直接通过length读取字符串长度,也不可以直接通过下标直接访问数据元素

使用的方法是:强制类型转换为bytes

其中," " 和‘ ’都可以表示

pragma solidity ^0.4.0;

contract first{
    string public str = 'hello world';
    function getstr() returns(uint){
        return bytes(str).length;
    }
    function changestr() {
        bytes(str)[0]='b';
    }
}

string类型,特殊字和英文字符数字字母占一个字节,中文汉字和中文字符占3个字节

pragma solidity ^0.4.0;

contract first{
    string public strCN ="你好,世界";    //中文标点,逗号
    string public strSY = "%$#@!";
    string public strCNSY = ",。";    //中文标点,逗号和句号
    string public str = 'hello world';
    function getstr() view returns(uint){
        return bytes(str).length;  
    }
    function getstr1() view returns(uint){
        return bytes(strCN).length;
    }
    function getstr2() view returns(uint){
        return bytes(strCNSY).length;
    }
}

结果为

 bytes数组转化为string,强制类型转化

pragma solidity ^0.4.0;

contract BytesToString{
    bytes public byt = new bytes(2);
    function Init(){
        byt[0] = 0x7a;
        byt[1] = 0x68; 
    }
    function bytesToString()view returns(string){
        return string(byt);
    }
}

数组

固定长度数组

从前到后截断,在末尾补充0

pragma solidity ^0.4.0;

contract first{
    bytes6 public a = 0x1929192031;
    function getbyte1() view returns(bytes1){
        return bytes1(a);
    }
    function getbyte4()view returns(bytes4){
        return bytes4(a);
    }
    function getbyte18()view returns(bytes12){
        return bytes12(a);
    }
}

可变长度数组

bytes a = new bytes(2);

 将固定长度数组赋值给可变长度数组

pragma solidity ^0.4.0;

contract first{
    bytes6 public str = 0x1929192031;
    function getNewStr()view returns(bytes){
        // 函数内部加上 memory
        bytes memory newstr = new bytes(str.length);
        //length为uint类型,因此i要写成uint
        for(uint i = 0; i < str.length; ++i){
            newstr[i] = str[i];
        }
        return newstr;
    }
}

 

猜你喜欢

转载自www.cnblogs.com/lhw-/p/10638729.html
今日推荐