22

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

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
tObi
  • 1,864
  • 3
  • 20
  • 32
  • As a general advise, usually (not always) you can design your programs so that you do not need to do string concatenation, or any string operations in Solidity. Smart contracts and blockchain virtual machines are not intended for string operations, so with a smarter architecture you can avoid it. – Mikko Ohtamaa Oct 04 '21 at 08:08

14 Answers14

26

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.

Community
  • 1
  • 1
eth
  • 842
  • 9
  • 14
  • I have deployed smart contract with s string, how to read the string? – Tomasz Waszczyk Jul 26 '18 at 11:47
  • 1
    @TomaszWaszczyk If the string is `public` use its accessor, otherwise the contract needs a function that returns the string. If you are "calling" the smart contract function, this might help https://ethereum.stackexchange.com/questions/765/what-is-the-difference-between-a-transaction-and-a-call because there are different ways of "calling" a smart contract. – eth Aug 12 '18 at 02:25
16

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.

12

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");
    }
}
sunwarr10r
  • 4,420
  • 8
  • 54
  • 109
8

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.

6

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"
Justin
  • 4,434
  • 4
  • 28
  • 37
2

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)));
    }
Antier Solutions
  • 1,326
  • 7
  • 10
2

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

Aminadav Glickshtein
  • 23,232
  • 12
  • 77
  • 117
2

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));
       } 
    }
Vaibhav Gaikwad
  • 811
  • 2
  • 12
  • 21
2

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);
    }
}
Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • Generally, there is no reason to work with strings in Solidity. Usually, it is a sign of bad architectural design or cluelessness about blockchain technology. – Mikko Ohtamaa Aug 19 '22 at 08:37
0

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

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

}
John Bradshaw
  • 179
  • 1
  • 16
0

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

Dev
  • 665
  • 1
  • 4
  • 12
0

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

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