在 Solidity 中将字符串转换为数组

String conversion to Array in Solidity

在 Solidity 中,有没有一种方法可以使用分隔符将我的字符串文本转换为数组以识别字符串中的复合部分

示例

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

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

没有为此内置的 method/function,但您可以使用 solidity-stringutils。然后

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

Crema 的回答几乎是正确的,但请注意,对于 n 个部分,我们有 n-1 个分隔符。修改他的代码给我们:

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

更新的答案,适用于最新的编译器

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