3
votes

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
Food for thought: every operation in EVM costs gas (which is money), so while doing this is possible, I'd not recommend doing this kind of processing in EVM to save cost. You should do all of these processing offline (e.g. before passing it to the contract), and only use the contract to execute logic that must be done on the blockchain (e.g. storing values) - Dat Nguyen
@Dat It comes down to priorities. What costs more money, multiple oraclize_query calls returning single bits of data, or a single call that gets split it up in the contract. - Marcelo Mason

3 Answers

2
votes

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

There is no built-in method/function for this but you can use solidity-stringutils. then

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));
        for(uint i = 0; i < parts.length; i++) {
           parts[i] = s.split(delim).toString();
        }
    }
}
2
votes

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