String concatenation in solidity?
Asked Answered
W

14

23

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

Warden answered 22/8, 2015 at 15:12 Comment(1)
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.Colorant
H
27

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.

Heidiheidie answered 29/5, 2016 at 11:50 Comment(2)
I have deployed smart contract with s string, how to read the string?Borstal
@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 ethereum.stackexchange.com/questions/765/… because there are different ways of "calling" a smart contract.Heidiheidie
N
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.

Nertie answered 26/8, 2015 at 18:58 Comment(1)
This answer is not up to date anymore. See the other ones.Pelerine
P
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");
    }
}
Princeling answered 27/2, 2018 at 17:28 Comment(1)
the second for loop contains an error, should be _newValue[j++] = _valueBytes[i];Subset
A
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.

Agogue answered 8/4, 2016 at 13:49 Comment(0)
D
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"
Dirndl answered 16/8, 2019 at 21:57 Comment(0)
T
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)));
    }
Theresa answered 19/1, 2021 at 5:0 Comment(1)
What is "/" for?Bohemia
A
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 :)

Allusion answered 4/10, 2021 at 7:47 Comment(0)
A
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));
       } 
    }
Agalloch answered 7/12, 2021 at 17:10 Comment(0)
P
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);
    }
}
Pluralize answered 19/8, 2022 at 1:19 Comment(1)
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.Colorant
M
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);
}
Mesentery answered 15/8, 2019 at 13:41 Comment(0)
N
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;
    }

}
Neighborhood answered 4/4, 2021 at 20:30 Comment(0)
T
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

Tevere answered 11/11, 2021 at 17:19 Comment(0)
C
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
}
Counterword answered 4/2, 2022 at 6:50 Comment(0)
P
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"
    }
}
Prog answered 4/2, 2022 at 13:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.