tObi
tObi

Reputation: 1942

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. :/

Upvotes: 23

Views: 27877

Answers (14)

Justin
Justin

Reputation: 4624

UPDATE [2023-07-28]:
See Freddie von Stange's answer from: https://ethereum.stackexchange.com/questions/729/how-to-concatenate-strings-in-solidity

tldr;

As of Feb 2022, in Solidity v0.8.12 you can now concatenate strings in a simpler fashion!

string.concat(s1, s2)

Taken directly from the solidity docs on strings and bytes:


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"

Upvotes: 6

Yilmaz
Yilmaz

Reputation: 49661

In solidity, working with a string is a headache. If you want to perform string action, you have to consider converting string to byte and then convert back to string again. this demo contract will concatenate strings

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

contract String{   
    function concatenate(string memory firstName,string memory lastName) public pure returns (string memory fullName)  {
        bytes memory full=string.concat(bytes(firstName),bytes(lastName));
        return string(full);
    }
}

Upvotes: 2

Mustafa Demirci
Mustafa Demirci

Reputation: 31

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"
    }
}

Upvotes: 0

Jedsada Tiwongvorakul
Jedsada Tiwongvorakul

Reputation: 79

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
}

Upvotes: 0

Vaibhav Gaikwad
Vaibhav Gaikwad

Reputation: 821

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

Upvotes: 2

Issei Kumagai
Issei Kumagai

Reputation: 685

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

Upvotes: 0

Yasir Aqeel
Yasir Aqeel

Reputation: 21

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 :)

Upvotes: 2

John Bradshaw
John Bradshaw

Reputation: 189

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

}

Upvotes: 0

sunwarr10r
sunwarr10r

Reputation: 4797

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

Upvotes: 12

Antier Solutions
Antier Solutions

Reputation: 1402

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

Upvotes: 2

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

Upvotes: 0

eth
eth

Reputation: 862

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.

Upvotes: 27

Sasha Zezulinsky
Sasha Zezulinsky

Reputation: 1786

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.

Upvotes: 8

Andreas Olofsson
Andreas Olofsson

Reputation: 177

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.

Upvotes: 16

Related Questions