导入
字符串
了解 Solidity 中的字符串。
...
Solidity 字符串示例,使用零基索引
1// SPDX-License-Identifier: MIT 2pragma solidity ^0.8.17; 3 4contract HelloWorld { 5 // greet 变量类型为字符串,使用双引号 ("") 6 string public greet = "Hello World!"; 7 // welcome 变量类型为字符串,使用单引号 ('') 8 string public welcome = 'Hello World!'; 9 10 string public word; 11 12 // 使用函数设置字符串 13 function setString() public { 14 word = "hey"; 15 } 16 17 // 使用函数通过传入新字符串参数来更新字符串 18 function updateString(string memory _word) public { 19 word = _word; 20 } 21}
1// SPDX-License-Identifier: MIT 2pragma solidity ^0.8.17; 3 4contract ByteToString { 5 function convertToString() public pure returns(string memory) { 6 // 初始化 bytes 类型数据 7 bytes memory welcome = "Hello World"; 8 // 使用 string 构造函数将 bytes 转换为字符串 9 string memory convertedString = string(welcome); 10 // 返回转换后的字符串 11 return convertedString; 12 } 13}
1// SPDX-License-Identifier: MIT 2pragma solidity ^0.8.17; 3 4contract StringToByte { 5 function convertToBytes() public pure returns(bytes memory) { 6 string memory greet = "hello"; 7 // 使用 bytes 构造函数 8 bytes memory stringByte = bytes(greet); 9 return stringByte; 10 } 11}
1// SPDX-License-Identifier: MIT 2pragma solidity ^0.8.17; 3 4contract StringLengthCalculator { 5 // 获取字符串长度的函数 6 function getStringLength(string memory _word) public pure returns (uint256) { 7 bytes memory stringBytes = bytes(_word); // 将字符串转换为字节数组 8 return stringBytes.length; // 返回字节数组的长度 9 } 10 // 获取示例单词 "Hello" 的长度 11 function getExampleWordLength() public pure returns (uint256) { 12 return getStringLength("Hello"); 13 } 14}