2015-08-22 27 views

回答

9

不能連接字符串。您也無法檢查等於(str0 == str1)。字符串類型最近才添加回語言,所以它可能需要一段時間,直到所有這些工作。你可以做什麼(他們最近添加的)是使用字符串作爲映射關鍵字。

您指向的連接是如何根據字段類型等計算存儲地址,但這是由編譯器處理的。

7

You have to do it manually for now

密實度不提供內置的字符串連接和字符串比較。
但是,您可以找到實現字符串連接和比較的庫和契約。

StringUtils.sol庫實現字符串比較。
Oraclize contract srtConcat function實現字符串連接。

如果需要連接以獲取結果字符串的散列值,請注意Solidity中有內置的散列函數:sha256ripemd160sha3。它們在計算哈希之前需要可變數量的參數並執行連接。

7

Ethereum Stack Exchange:

一個library的回答可以用,例如:

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

contract C { 
    using strings for *; 
    string public s; 

    function foo(string s1, string s2) { 
    s = s1.toSlice().concat(s2.toSlice()); 
    } 
} 

使用上述的quick test,你可以按需要修改。


由於concatenating strings needs to be done manually for now,並在合同中會消耗不必要的氣體這樣做(新的字符串已被分配,然後每個字符寫的),這是值得考慮什麼是需要字符串連接的使用情況?

如果可以用某種方式編寫DApp,以便前端連接字符串,然後將它傳遞給合同進行處理,則這可能是一個更好的設計。

或者,如果合同要哈希一個長字符串,請注意,所有內置的密實度的散列函數(sha256ripemd160sha3)帶有可變數量的參數,並計算散列之前執行級聯。

1

下面是在Solidity中連接字符串的另一種方法。它也顯示在這tutorial

pragma solidity ^0.4.19; 

library Strings { 

    function concat(string _base, string _value) internal returns (string) { 
     bytes memory _baseBytes = bytes(_base); 
     bytes memory _valueBytes = bytes(_value); 

     string memory _tmpValue = new string(_baseBytes.length + _valueBytes.length); 
     bytes memory _newValue = bytes(_tmpValue); 

     uint i; 
     uint j; 

     for(i=0; i<_baseBytes.length; i++) { 
      _newValue[j++] = _baseBytes[i]; 
     } 

     for(i=0; i<_valueBytes.length; i++) { 
      _newValue[j++] = _valueBytes[i++]; 
     } 

     return string(_newValue); 
    } 

} 

contract TestString { 

    using Strings for string; 

    function testConcat(string _base) returns (string) { 
     return _base.concat("_Peter"); 
    } 
}