字符串使用 “”或’’表示.

字符串基本使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
pragma solidity ^0.8.0;

contract StringDemo{
string _name;

constructor(string memory name) {
_name = name;
}

function setName(string memory name) public {
_name = name;
}

function getName() view public returns (string memory){
return _name;
}
}

字符串的比较

1
2
3
4
5
6
7
8
9
10
pragma solidity ^0.8.0;

contract StringDemo{

//...

function compareString(string memory str1,string memory str2) pure public returns(bool){
return keccak256(abi.encodePacked(str1))==keccak256(abi.encodePacked(str2));
}
}

字符串的合并

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

pragma solidity ^0.8.0;

contract StringDemo{

//...

function join1(string memory str1,string memory str2) pure public returns(bytes memory){
return abi.encodePacked(str1,str2);
}

function join2(string memory str1,string memory str2) pure public returns(string memory){
return string(abi.encodePacked(str1,str2));
}
}