How to convert string to array in Solidity? Solidity by example?
This tutorial talks about how to convert a string of text into an array using a string separator.
The string is a valid value type in Solidity stores text content.
Array in solidity is a reference type that contains a group of data types stored under a single name variable. Values are retrieved using an index starting from zero.
There is no inbuilt function to convert string to array in solidity.
For example, a given input string contains
one-two-three-four
The above string is parsed and delimited by a hyphen(-) Output returns an array
one
two
three
four
How to Convert string to array in solidity with separator
This example uses stringutils🔗 of this package in solidity code.
The solidity-stringutils
string library provides string manipulation utility functions.
First import the custom library in a contract with the using
keyword.
First, convert the original and delimiter string to slice using the toslice()
method.
Create a new string array with the count method, return a string array of string[] memory
Create an array type with the iterated string memory array and create an array of strings.
// 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();
}
}
}