'String concatenation in solidity?

How do I concatenate strings in solidity?

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

seems not to work..

I looked up the documentation 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.. :/



Solution 1:[1]

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.

Solution 2:[2]

You can't concatenate strings. You also can not check equals (str0 == str1) yet. The string type was just recently added back to the language so it will probably take a while until all of this works. What you can do (which they recently added) is to use strings as keys for mappings.

The concatenation you're pointing to is how storage addresses are computed based on field types and such, but that's handled by the compiler.

Solution 3:[3]

Here is another way to concat strings in Solidity. It is also shown in this 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");
    }
}

Solution 4:[4]

You have to do it manually for now

Solidity doesn't provide built-in string concatenation and string comparison.
However, you can find libraries and contracts that implement string concatenation and comparison.

StringUtils.sol library implements string comparison.
Oraclize contract srtConcat function implements string concatenation.

If you need concatenation to get a hash of a result string, note that there are built-in hashing functions in Solidity: sha256, ripemd160, sha3. They take a variable number of arguments and perform the concatenation before computing the hash.

Solution 5:[5]

You could leverage abi.encodePacked:

bytes memory b;

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

string memory s = string(b);
// s == "hello world"

Solution 6:[6]

you can do it very easily with the low-level function of solidity with abi.encodePacked(str,b)

one important thing to remember is , first typecast it to string ie: string(abi.encodePacked(str, b))

your function will return

return string(abi.encodePacked(str, b));

its easy and gas saving too :)

Solution 7:[7]

Solidity does not offer a native way to concatenate strings so we can use abi.encodePacked(). Please refer Doc Link for more information

// SPDX-License-Identifier: GPL-3.0

    pragma solidity >=0.5.0 <0.9.0;


   contract AX{
      string public s1 = "aaa";
      string public s2 = "bbb";
      string public new_str;
 
      function concatenate() public {
         new_str = string(abi.encodePacked(s1, s2));
       } 
    }

Solution 8:[8]

I used this method to concat strings. Hope this is helpful

function cancat(string memory a, string memory b) public view returns(string memory){
        return(string(abi.encodePacked(a,"/",b)));
    }

Solution 9:[9]

Examples above do not work perfect. For example, try concat these values

["10","11","12","13","133"] and you will get ["1","1","1","1","13"]

There is some bug.

And you also do not need use Library for it. Because library is very huge for it.

Use this method:

function concat(string _a, string _b) constant returns (string){
    bytes memory bytes_a = bytes(_a);
    bytes memory bytes_b = bytes(_b);
    string memory length_ab = new string(bytes_a.length + bytes_b.length);
    bytes memory bytes_c = bytes(length_ab);
    uint k = 0;
    for (uint i = 0; i < bytes_a.length; i++) bytes_c[k++] = bytes_a[i];
    for (i = 0; i < bytes_b.length; i++) bytes_c[k++] = bytes_b[i];
    return string(bytes_c);
}

Solution 10:[10]

You can do this with the ABI encoder. Solidity can not concatenate strings natiely because they are dynamically sized. You have to hash them to 32bytes.

pragma solidity 0.5.0;
pragma experimental ABIEncoderV2;


contract StringUtils {

    function conc( string memory tex) public payable returns(string 
                   memory result){
        string memory _result = string(abi.encodePacked('-->', ": ", tex));
        return _result;
    }

}

Solution 11:[11]

Compared to languages such as Python and JavaScript, there is no direct way of doing this in Solidity. I would do something like the below to concatenate two strings:

//SPDX-License-Identifier: GPL-3.0
 
pragma solidity >=0.7.0 < 0.9.0;

contract test {
    function appendStrings(string memory string1, string memory string2) public pure returns(string memory) {
        return string(abi.encodePacked(string1, string2));
    }
}

Please see the screenshot below for the result of concatenating two strings ('asdf' and 'sdf') in Remix Ethereum IDE.

enter image description here

Solution 12:[12]

You can use this approach to concat and check equal string.


// concat strgin
string memory result = string(abi. encodePacked("Hello", "World"));


// check qual
if (keccak256(abi.encodePacked("banana")) == keccak256(abi.encodePacked("banana"))) {
  // your logic here
}

Solution 13:[13]

After 0.8.4 version of Solidity, you can now concat bytes without using encodePacked()

See the issue: here

//SPDX-License-Identifier: GPT-3
pragma solidity >=0.8.4;

library Strings {
    
    function concat(string memory a, string memory b) internal pure returns (string memory) {
        return string(bytes.concat(bytes(a),bytes(b)));
    }
}

Usage:

contract Implementation {
    using Strings for string;

    string a = "first";
    string b = "second";
    string public c;
    
    constructor() {
        c = a.concat(b); // "firstsecond"
    }
}