solidity[11]-字符串

字符串


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 getLength2() 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 getLength1() public view returns(uint){
        return bytes(name1).length;
    }
    function  getBytes1() public view returns(bytes){

        return bytes(name1);
    }

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

        return bytes(name2);
    }
}

总结

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

郑建勋(jonson)区块链工程师 & Web工程师

灾难总是接踵而至,这正是世间的常理。你以为只要哭诉一下,就会有谁来救你吗?如果失败了,就只能说明我不过是如此程度的男人。

发布了59 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weishixianglian/article/details/84112828