How to convert string to array in Solidity? Solidity by example?
This tutorial discusses how to convert a string of text into an array using a string separator.
In Solidity, a string
is a valid value type that stores text content.
An array
in Solidity is a reference type that contains a group of data types stored under a single named variable. Values are retrieved using an index starting from zero.
Solidity does not have an inbuilt function to convert a string to an array.
For example, consider a given input string that 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 offers utility functions for string manipulation.
First, import the custom library into a contract using the using keyword.
Next, convert the original and delimiter strings to slices using the toslice()
method. Create a new string array with the count
method, which returns a string array
of string[]
memory. Finally, 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();
}
}
}