案例
字符串可以通过""
或者''
来表示字符串的值,Solidity中的string
字符串不像C语言
一样以\0
结束,比如我的微信号liyc1215
这个字符串的长度就为我们所看见的字母的个数,它的长度为8
。
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.7.0;
contract StringLiterals{
string _name; // 状态变量
//构造函数
constructor() public {
// 将我的微信号初始化
_name = "liyc1215";
}
// set方法
function setString(string memory name) public {
_name = name;
}
// get方法
function name() view public returns (string memory) {
return _name;
}
}
备注:string
字符串不能通过length
方法获取其长度。
字符串比较与合并
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.7.0;
contract StringLiterals{
// 比较s1和s2是否相等,相等返回true,不相等返回false
function compareEqual(string memory s1,string memory s2) pure public returns(bool) {
return keccak256(abi.encodePacked(s1)) == keccak256(abi.encodePacked(s2));
}
// 将s1和s2合并为一个字节数组
function mergeS1AndS2ReturnBytes(string memory s1,string memory s2) pure public returns(bytes memory) {
return abi.encodePacked(s1, s2);
}
// 将s1和s2合并为一个字节数组转换为string
function mergeS1AndS2ReturnString(string memory s1,string memory s2) pure public returns(string memory) {
return string(abi.encodePacked(s1, s2));
}
}
keccak256(abi.encodePacked(s1)) == keccak256(abi.encodePacked(s2))
可以通过这个方法比较两个字符串是否相等。abi.encodePacked(s1, s2)
:通过这个方法进行字符串合并拼接。
最新评论