字符串

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

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

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