String concatenation in solidity?

tObi picture tObi · Aug 22, 2015 · Viewed 15.3k times · Source

how do i concatenate strings in solidity?

var str = 'asdf'
var b = str + 'sdf'

seems not to work..

I looked up the documentation (https://github.com/ethereum/wiki/wiki/Solidity-Tutorial#elementary-types-value-types) and there is not much mentioned about string concatenation. But it is stated that it works with the dot ('.') ?

"[...] a mapping key k is located at sha3(k . p) where . is concatenation."

Didn't work out for me too.. :/

Answer

eth picture eth · May 29, 2016

An answer from the Ethereum Stack Exchange:

A library can be used, for example:

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

Use the above for a quick test that you can modify for your needs.


Since concatenating strings needs to be done manually for now, and doing so in a contract may consume unnecessary gas (new string has to be allocated and then each character written), it is worth considering what's the use case that needs string concatenation?

If the DApp can be written in a way so that the frontend concatenates the strings, and then passes it to the contract for processing, this could be a better design.

Or, if a contract wants to hash a single long string, note that all the built-in hashing functions in Solidity (sha256, ripemd160, sha3) take a variable number of arguments and will perform the concatenation before computing the hash.