2015-08-22 22 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"); 
    } 
}