Concatenate Strings in Solidity

Published by Mario Oettler on

Last Updated on 12. June 2023 by Mario Oettler

Concatenating two strings in Solidity can be done this way:

String string_3 = string.concat(string_1, string_2);

This is possible since solidity 0.8.12.

Before, concatenating two strings in Solidity was done by using abi.encodePacked(),

        bytes memory cBytes = abi.encodePacked(_a, _b);

        string memory c = string(cBytes);

String manipulation in Solidity is very rudimentary (aka not existent). Those operations should be done outside of a transaction and only the result should be submitted to the smart contract.

Example

The following code example shows both ways:

pragma solidity 0.8.20;

contract concatStrings{

    function concatMyStrings(string memory _a, string memory _b) public view returns(string memory c){
        return(string.concat(_a, _b));
    }

    function concatMyStrings2(string memory _a, string memory _b) public view returns(string memory c){
        bytes memory cBytes = abi.encodePacked(_a, _b);
        string memory c = string(cBytes);
        return c;
    }
}
Categories:

https://blockchain-academy.hs-mittweida.de/wp-content/uploads/2021/04/logo_bcam_rgb_gross.png

Welcome

Blockchain Academy

Continue with credential

No account yet?

Powered by Hidy

Register with Hidy


Register
Sign in

We need the following credential to register:

please select:

To create a new account, we need the following data from you:

We would appreciate the following additional information from you for the creation of your account:

Welcome

Blockchain Academy

Continue with credential

Already have an account?

Powered by Hidy

Sign in with Hidy


Register
Sign in

We need the following credential to log in:

please select:
Do you need assistance?
Click here to open chat.

Privacy Notice: This chat sends your questions to an external AI server.
How can we help you?
  • Please note: All questions, chat history, and feedback are sent to an external AI server for processing. Do not share sensitive personal information.

    All responses are generated by AI. Independently verify and fact-check all information before use.
  • No Chat History yet, start talking...