Search code examples
arraysstringethereumsolidity

String conversion to Array in Solidity


In Solidity, is there a way I can convert my string text to an array using a separator to identify the composite parts within the string

Example

mystring = "This-Is-A-Problem";

to

myArray = [This,Is,A,Problem];   // using hyphen as separator

Solution

  • The answer by Crema is almost correct, but note that for n parts we have n-1 delimiters. Modifying his code gives us:

    import "github.com/Arachnid/solidity-stringutils/strings.sol";
    
    contract Contract {
       using strings for *;
    
       // ...
    
       function smt() {
        var s = ""This-Is-A-Problem"".toSlice();
        var delim = "-".toSlice();
        var parts = new string[](s.count(delim) + 1);
    
        for(uint i = 0; i < parts.length; i++) {
           parts[i] = s.split(delim).toString();
        }
       }
    }