pragma solidity ^0.8.0;
import "github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol"; // 引入这个包
contract test {
bytes9 public g = 0x6c697975656368756e;
string public name = "hell world";
function gByteLength() public view returns (uint) {
return g.length;
}
function nameBytes() public view returns (bytes memory) {
return bytes(name);
}
function nameLength() public view returns (uint) {
return bytes(name).length;
}
function setNameFirstByteForL(bytes1 z) public {
// 0x4c => "L"
bytes(name)[0] = z;
}
using strings for *;
string public myStr;
string public niceName = unicode"陈小浩同学a";
function foo(string memory strPart) public {
myStr = myStr.toSlice().concat(strPart.toSlice());
}
function getNiceNameLength() public view returns (uint) {
return bytes(niceName).length;
}
function getNiceNameLength1() public view returns (uint) {
return niceName.toSlice().len();
}
function testEndsWith() public {
strings.slice memory s = "foobar".toSlice();
require(s.endsWith("bar".toSlice()),"end bar");
}
bytes public data;
function testBytes(bytes1 b) public {
data.push(b);
}
address public owner;
constructor() {
owner = msg.sender;
}
function destroy() public {
require(msg.sender == owner, "You are not the owner");
//deprecated
selfdestruct(payable(owner));
}
}
function encode() public view returns (bytes memory result){
result = abi.encode(x,addr,name,array);
}
function encodePacked() public view returns (bytes memory result){
result = abi.encodePacked(x,addr,name,array);
}
function encodeWithSignature() public view returns (bytes memory result){
result = abi.encodeWithSignature("foo(uint256,address,string,uint256[2])", x, addr, name, array);
}
function encodeWithSelector() public view returns(bytes memory result) {
result = abi.encodeWithSelector(bytes4(keccak256("foo(uint256,address,string,uint256[2])")), x, addr, name, array);
}
function decode(bytes memory data) public pure returns(uint dx, address daddr, string memory dname, uint[2] memory darray) {
(dx, daddr, dname, darray) = abi.decode(data, (uint, address, string, uint[2]));
}
智能合约之字符串处理
于 2024-12-25 17:06:35 首次发布