How to Concatenate two Strings using Solidity

How to Concatenate two Strings using Solidity

String manipulation.

Concatenating two strings in solidity means combining the two strings to create one single string.

For a long while concatenating two strings on the Ethereum targetted Smart Contract language wasn't possible without having to undergo some kind of lengthy workaround, using functions like abi.encodedpacked (v0.8.11 and younger) or libraries like the one here.

For the longest time, there wasn't any function or built-in way for concatenating strings in Solidity, unlike other high-level programming languages like C, Python, or JavaScript, but fortunately, as it is a fast-growing and fast-developing language, the developer's released version 0.8.12, which now supports concatenation of strings using the string.concat() function.

Using a Manual Bytes Array Manipulation

Now before I show you how to do this in a more current way, let's go over how people used to do this in the past and make a comparison between both methods.

First, we'll manually create a workaround using an iterative method:

pragma solidity ^0.8.0;

contract StringConcatenation {
    // Function to concatenate two strings
    function concatenateStrings(string memory a, string memory b) public pure returns (string memory) {
        // Convert input strings to byte arrays
        bytes memory byteArrayA = bytes(a);
        bytes memory byteArrayB = bytes(b);

        // Calculate total length of the concatenated string
        uint totalLength = byteArrayA.length + byteArrayB.length;

        // Create a new dynamic byte array of the total length
        bytes memory result = new bytes(totalLength);

        // Loop through the first input string and copy its bytes to the result array
        uint i;
        uint j;
        for (i = 0; i < byteArrayA.length; i++) {
            result[j++] = byteArrayA[i];
        }

        // Loop through the second input string and copy its bytes to the result array
        for (i = 0; i < byteArrayB.length; i++) {
            result[j++] = byteArrayB[i];
        }

        // Convert the result byte array back to a string and return it
        return string(result);
    }
}
  • The function concatenateStrings(string memory a, string memory b) public pure returns (string memory) takes two input strings a and b as parameters, and returns a concatenated string.

  • bytes memory byteArrayA = bytes(a); and bytes memory byteArrayB = bytes(b); convert the input strings a and b into byte arrays.

  • uint totalLength = byteArrayA.length + byteArrayB.length; calculates the total length of the concatenated string by summing the lengths of byteArrayA and byteArrayB.

  • bytes memory result = new bytes(totalLength); creates a new dynamic byte array result with the calculated total length. This array will store the concatenated string.

  • The first loop for (i = 0; i < byteArrayA.length; i++) iterates through the bytes of the first input string (byteArrayA) and copies them into the result array. The j variable keeps track of the index in the result array.

  • Similarly, the second loop for (i = 0; i < byteArrayB.length; i++) iterates through the bytes of the second input string (byteArrayB) and copies them into the result array, starting from where the first loop left off.

  • return string(result); converts the result byte array back into a string using string(result) and returns it as the concatenated string.

Summary: The above code takes two input strings, converts them to byte arrays, calculates the total length, creates a new byte array, copies the bytes from each input string into the result array, and finally converts the result array back into a string to obtain the concatenated string.

This is how strings are concatenated through manual byte array manipulation. Let's explore a shorter method of concatenating strings.

Using the abi.encodePacked

Using the abi.encodePacked() function, strings can be concatenated much more efficiently.

Let's take an example down below:

pragma solidity ^0.8.11;

contract StringConcatenation {
    function concatenateStrings(string memory a, string memory b) public pure returns (string memory) {
        bytes memory concatenatedBytes = abi.encodePacked(a, b);
        return string(concatenatedBytes);
    }
}
  • The abi.encodePacked function is used to concatenate the strings a and b efficiently. It takes any number of arguments and packs them tightly without any padding or separators.

  • bytes memory concatenatedBytes = abi.encodePacked(a, b); packs the strings a and b into a byte array called concatenatedBytes. This single line replaces the manual byte array creation and copying loops from the previous version.

  • return string(concatenatedBytes); converts the concatenatedBytes byte array back into a string and returns it as the concatenated string.

By utilizing abi.encodePacked, you can achieve string concatenation more concisely and efficiently without the need for manual byte array manipulation.

Using the string.concat() function

Now, let us try concatenating two strings using the latest developed version (v0.8.12) from the developers. The string.concat() function.

pragma solidity 0.8.12;

contract StringConcatenation {
    function concatenateStings(string memory a, string memory b) public pure returns (string memory) {
        return string.concat(a,b);
    }
}
  • The string.concat() function simply takes the first string and the second string and simply concatenates two of them together to form one string without having to do any further work or use any other function.

As seen in the image above, this method is very much supported by the Solidity documentation and is advised to be used by developers when trying to concatenate two strings into one.

If you liked this and found it informative, leave a like, or a comment, or reach out to me on any of my socials for hiring, or maybe a good blockchain discussion by clicking on this link.