String conversion to Array in Solidity

Viewed 5732

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
3 Answers

updated answer, works on latest compiler

import "github.com/Arachnid/solidity-stringutils/strings.sol";

contract Contract {                                                            
    using strings for *;                                                       

    function smt() public pure {                                               
        strings.slice memory s = "This-Is-A-Problem".toSlice();                
        strings.slice memory delim = "-".toSlice();                            
        string[] memory parts = new string[](s.count(delim));                  
        for (uint i = 0; i < parts.length; i++) {                              
           parts[i] = s.split(delim).toString();                               
        }                                                                      
    }                                                                          
}  

https://ethfiddle.com/TgY5JxLKvn

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();
    }
   }
}
Related