在Solidity中将字符串转换为Array

时间:2017-05-25 11:37:31

标签: arrays string ethereum solidity

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

实施例

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

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

3 个答案:

答案 0 :(得分:2)

此处没有内置方法/功能,但您可以使用solidity-stringutils。然后

{{1}}

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

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