字符串连接是否可靠?

tOb*_*Obi 17 ethereum solidity

我如何连接字符串的可靠性?

var str = 'asdf'
var b = str + 'sdf'
Run Code Online (Sandbox Code Playgroud)

似乎不起作用..

我查阅了文档(https://github.com/ethereum/wiki/wiki/Solidity-Tutorial#elementary-types-value-types),并没有提到有关字符串连接的内容.但据说它适用于点('.')?

"[...] a mapping key k is located at sha3(k . p) where . is concatenation."
Run Code Online (Sandbox Code Playgroud)

也没为我工作..:/

eth*_*eth 18

以太坊堆栈交换的答案:

可使用,例如:

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());
  }
}
Run Code Online (Sandbox Code Playgroud)

使用上面的快速测试,您可以根据需要进行修改.


由于串联字符串现在需要手动完成,并且在合同中这样做可能会消耗不必要的气体(必须分配新的字符串然后写入每个字符),值得考虑需要字符串连接的用例是什么?

如果DApp可以以某种方式编写,以便前端连接字符串,然后将其传递给合同进行处理,这可能是更好的设计.

或者,如果合同要哈希一个长字符串,请注意,所有的内置散列函数的密实度(sha256,ripemd160,sha3),带可变数量的参数,并计算散列之前进行级联.


小智 17

你不能连接字符串.你也无法检查equals(str0 == str1).字符串类型最近刚刚添加回语言,所以它可能需要一段时间才能完成.你能做什么(他们最近添加的)是使用字符串作为映射的键.

您指向的串联是如何根据字段类型等计算存储地址,但这是由编译器处理的.

  • 这个答案不再是最新的。参见其他。 (2认同)

Sas*_*sky 9

你现在必须手动完成

Solidity不提供内置字符串连接和字符串比较.
但是,您可以找到实现字符串连接和比较的库和契约.

StringUtils.sol库实现字符串比较.
Oraclize合同srtConcat函数实现字符串连接.

如果你需要级联得到一个结果字符串的哈希值,注意有内置的密实度的散列函数:sha256,ripemd160,sha3.它们采用可变数量的参数并在计算哈希值之前执行连接.


sai*_*tam 7

这是另一种在Solidity中连接字符串的方法.它也显示在本教程中:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 第二个 for 循环包含错误,应该是 `_newValue[j++] = _valueBytes[i];` (4认同)

Jus*_*tin 6

更新[2023-07-28]:
请参阅Freddie von Stange 的回答: https: //ethereum.stackexchange.com/questions/729/how-to-concatenate-strings-in-solidity

太棒了;

截至 2022 年 2 月,在 Solidity v0.8.12 中,您现在可以以更简单的方式连接字符串!

string.concat(s1, s2)
Run Code Online (Sandbox Code Playgroud)

直接取自关于字符串和字节的 Solidity 文档:


您可以利用abi.encodePacked

bytes memory b;

b = abi.encodePacked("hello");
b = abi.encodePacked(b, " world");

string memory s = string(b);
// s == "hello world"
Run Code Online (Sandbox Code Playgroud)