How to append the string to another in Solidity by example

This tutorial covers the process of string concatenation in Solidity, illustrating how to append one string to another.

For instance, let’s consider a scenario where you have two strings.

string str = 'hello'
string b = "world"

And output is

hello world

Appending strings in other programming languages like Java and JavaScript is straightforward, typically accomplished using the + operator or an append function/method.

However, it’s essential to note that Solidity lacks built-in support for an append function or the + operator when it comes to string manipulation.

It’s crucial to highlight that string manipulation in Solidity incurs a significant gas cost. Therefore, it is not recommended to extensively use string manipulation in the context of blockchain development or Solidity.

How to concatenate string in solidity with example

The solidity-stringutils library offers string manipulation functions, including the concat function within the strings.slice type.

In the following example, two strings are taken as input. The toSlice() function is employed to convert both Solidity string type objects to the strings.slice type. Subsequently, the concat function is utilized to append the strings.

Here’s an example code snippet for string appending in Solidity:

// SPDX-License-Identifier: GPL-3.0

pragma solidity ~0.4.14;
import "https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol";

contract MyContract {
  using strings for *;
  string public str;

  function append(string string1, string string2) {
    str = string1.toSlice().concat(string2.toSlice());
  }
}

Conclusion

Calling string append in Solidity is not straightforward due to the absence of built-in functions. It is an expensive operation in Solidity, so it is crucial to use string append judiciously when implementing it.