本教程讲述了如何使用字符串分离器将一串文本转换成一个数组。
字符串是Solidity中存储文本内容的有效价值类型。
solidity中的数组是一种参考类型,它包含了一组存储在单一名称变量下的数据类型,这些值使用从零开始的索引进行检索。
在solidity中没有内置的函数可以将字符串转换为数组。
例如,一个给定的输入字符串包含
one-two-three-four
上述字符串被解析并以连字符(-)为界,输出后返回一个数组
one
two
three
four
如何在solidity中用分隔符将字符串转换为数组?
这个例子在solidity代码中使用了这个包的stringutils。
solidity-stringutils string库提供了字符串操作的实用函数。
首先在合同中用using 关键字导入自定义库。
首先,用toslice()方法将原始和分隔符的字符串转换为slice。用count方法创建一个新的字符串数组,返回一个字符串[]内存的字符串数组 用迭代的字符串内存数组创建一个数组类型,并创建一个字符串数组。
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.4.1;
import "https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol";
contract Contract {
using strings for *;
function smt() public () {
strings.slice memory stringSlice = "one-two-three-four".toSlice();
strings.slice memory delimeterSlice = "-".toSlice();
string[] memory strings = new string[](stringSlice.count(delimeterSlice));
for (uint i = 0; i < strings.length; i++) {
strings[i] = stringSlice.split(delim).toString();
}
}
}