eatthecode.com

Solidity concatenate strings

Solidity concatenate strings

Introduction

In the old versions, Solidity didn’t offer a straightforward way to concatenate or compare strings as other programming languages.  Solidity with the new versions from v0.8.12 offers a simple string manipulation through standardized usage. string.concat is supported from Solidity v0.8.12. A string manipulation library can be used. There are libraries for JSON parsers. It is recommended to manipulation should not occur in the blockchain network. The use of the message system is strictly forbidden by the blockchain. Blockchain is a specialized back-end that depends on the representation of variables.

Solidity concatenate strings
Solidity concatenate strings

Solidity

String Concatenation in Solidity

The methods as abi.encodePacked() or bytes.concat() can be used in concatenating strings in solidity. If you are using older version of solidity (before v0.8.12), you can use the methods abi.encodePacked() or bytes.concat() but if you are using version v0.8.12 or recent, you can use string.concat

abi.encodePacked()

abi.encodePacked() can be used in string concatenation as the following example

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

contract StringConcatenation {
    function concatenateString(string memory string1, string memory string2)
        public
        pure
        returns (string memory)
    {
        return string(abi.encodePacked(string1, " ", string2));
    }
}

 

bytes.concat()

bytes.concat can be used in string concatenation as the following example

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

contract StringConcatenation {
    function concatenateString(string memory string1, string memory string2)
        public
        pure
        returns (string memory)
    {
        return string(bytes.concat(bytes(string1), " ", bytes(string2)));
    }
}

string.concat()

In solidity v0.8.12, string.concat can be used in string concatenation as the following example

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;

contract StringConcatenation {
    function concatenateString(string memory string1, string memory string2)
        public
        pure
        returns (string memory)
    {
        return string.concat(string1, string2);
    }
}

Conclusion

The string concatenation is not straightforward in solidity. In this post, I illustrated some ways to apply string concatenation as abi.encodePacked() or bytes.concat() with giving some coding examples. In solidity v0.8.12, string.concat can be used in string concatenation also and The post contains an example of this.

You can find sample solidity source codes at github Enjoy…!!!

I can help you to build such as software tools/snippets, you contact me from here

 
Exit mobile version