Solidity String – Complete tutorial

In this Solidity tutorial, we will discuss how to use the Solidity string data type using various examples in Solidity. Moreover, we will illustrate the following set of topics.

  • Solidity string
  • Solidity string example
  • Solidity string concatenation
  • Solidity string length
  • Solidity string comparison
  • Solidity string to bytes32
  • Solidity string to address
  • Solidity string array
  • Solidity string memory
  • Solidity string to uint256

Solidity String

Being a statically typed programming language, we need to define the data type for each variable in Solidity. Though Solidity supports many different types of data types, here in this tutorial, we will illustrate the use of a string data type.

So, just like several programming languages, we can define a variable of String data type in Solidity. And it accepts both double quotes () and single quotes () in String literals.

However, there are certain differences and limitations of using a string data type in Solidity. Here are some of the key reasons.

  • Solidity does not provide any built-in method to determine the length of a String.
  • It also does not provide any built-in method to concatenate 2 sets of strings.
  • In Solidity, we cannot directly fetch a substring from a particular string variable.
  • Also, we cannot replace any character value from a string in Solidity.

However, we can manually create a function in Solidity to implement any of the above-mentioned tasks.

Solidity String Example

Now, in Solidity, we can easily declare a variable of string data type using the following syntax.

pragma solidity 0.8.1;

contract ContractName {
   string var_name = "Sample";
}
  • So, in the above syntax, first, we are using the pragma directive to specify the Solidity version.
  • After this, we are defining a contract where we can specify the name of the contract in place of ContractName.
  • And within the contract, we are defining a string type variable where Sample is the string literal and var_name is the variable name.

Next, let’s use the above syntax to create a smart contract in Solidity that will return the value of the string variable. The code for the example is as follows.

// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.1;

contract StringExp {
    string public message = 'Hello from Ethereumdots';

    function setMessage(string memory _message) public {
        message = _message;
    }
}
  • In the above example, first, we are using the pragma directive to specify the Solidity version as 0.8.1.
  • After this, we are creating a contract named StringExp. Within this contract, we have declared a public string variable named message and also assigned a string value to it.
  • Next, we are also creating a function named setMessage to change the value of the message variable.

Now, to execute the above smart contract, we will be using the REMIX IDE. And first, we need to compile the contract and then deploy it under the JavaScript VM environment. After deployment, we can easily fetch the variable value by clicking on the message button.

Solidity String Example
Solidity String Example

We can also change the value of the message variable by specifying a new string value under the setMessage option.

Solidity String Datatype Example
Solidity String Datatype Example

Read: Solidity Array – Detailed Guide

Solidity String Length

In this section, we will discuss how to find the length of a string in Solidity. Additionally, we will also try to illustrate an example related to this implementation.

In many programming languages, we simply use a string method to calculate the length of a given string. For example, in Python, we generally use the len() function to find the string length.

However, this case is not the same for Solidity. Solidity does not facilitate any string method for calculating the length of a given string.

Still, there is an alternative method that we can use for this task. The steps for this implementation are as follows.

  • First, we will define a variable in a contract of string data type and also assign a certain value to it.
  • Then we will convert the string variable into bytes and then we will use the length method on bytes to get the length.
  • In the end, we will return the final result which will be of uint (unsigned 256-bit integer) data type.

Note: A unsigned integer in Solidity is simply a non-negative integer value.

Now, let’s execute an example related to the above implementation in Solidity. And the code for the example is given below.

 // SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.1; 

contract StringLength {   

    function getStrLen(string memory _str) public pure returns(uint) {
        
        uint strlen = bytes(_str).length;
        return strlen;

    }   
}
  • In the above example, first, we are using the pragma to specify the Solidity version as 0.8.1.
  • After this, we are creating a contract named StringLength and within the contract, we are creating a function named getStrLen.
  • Now, this function takes the string variable named _str, converts the string into bytes, calculates its length, and stores it in strlen variable.
  • And in the end, the function returns the value of strlen variable as a result.
Solidity String Length
Solidity String Length

Read: Solidity Function + Examples

Solidity String Concatenation

In this section, we will discuss some of the key methods to concatenate 2 string values in Solidity.

#1: By using the bytes.concat()

In the first method, we will use the same approach as discussed in the previous section. So, first, we will convert the string values into bytes and then we will use the bytes.concat() method to concatenate the values. And in the end, we will return the result by converting bytes back into a string.

Let’s understand this concept by executing an example in Solidity and the code for the example is given below.

 // SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.12;

contract StringConcat {
    function StrConcat(string memory str1, string memory str2) public pure returns (string memory){
        
       return string(bytes.concat(bytes(str1), " " ,bytes(str2)));
             
    } 
}
  • In the above example, we are using the Solidity version greater than 0.8.12.
  • After this, we are creating a contract named StringConcat and within the contract, we are creating a function named StrConcat.
  • Now, this function takes two string variables named str1 and str2 respectively, converts the string variables into bytes, and concatenates the two bytes variables.
  • In the end, the function returns the final concatenated value as a string.
Solidity String Concatenation
Solidity String Concatenation

Now, once the contract is successfully compiled, we are executing the contract by providing 2 string values as input. For str1, we provided “United” as a value and for str2, we provided “States” as an input value. And when we click on call, it will return “United States” as the final result.

#2: By using the string.concat()

The string.concat() function is available for solidity ^0.8.12 and it helps to concatenate multiple string values into one single string array.

So, for the second method, we will use the string.concat() function. And the example for this implementation is given below.

 // SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.12;

contract StringConcat {
    function StrConcat(string memory str1, string memory str2) public pure returns (string memory){
        
       return string.concat(str1, " ", str2);
             
    } 
}
  • In the above example, again, we are using the Solidity version greater than 0.8.12.
  • Next, we have created a contract named StringConcat and within the contract, we created a function named StrConcat.
  • Now, this function also takes two string variables named str1 and str2 respectively and returns a string array.
  • In the return statement, we are using the string.concat() function to concatenate both the values of str1 and str2. And it also adds a space between them.
Solidity String Concatenation Example
Solidity String Concatenation Example

After successfully compiling the above contract, we are executing the contract by providing 2 string values as input. For str1, we provided “New” as a value and for str2, we provided “Zealand” as an input value. And when we click on call, it will return “New Zealand” as the final result.

Read: Solidity Constructor

Solidity String Comparison

In this section, we will discuss how to compare string values in Solidity. But, again, Solidity does not support the use of comparison operators on the string. So, here also we are going to use a trick.

So, for the string comparison, first, we will calculate the keccak256-hash for each string. Then compares their results and returns TRUE or FALSE based upon the comparison. And the example for this illustration is given below.

 //SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.12;

contract StringCompare {
    function Compare(string memory strVal1, string memory strVal2) 
    public pure returns (bool){

        return keccak256(abi.encodePacked(strVal1)) == keccak256(abi.encodePacked(strVal2));     
        
    } 
}
  • In the above example, first, we are using the pragma to specify the Solidity version greater than 0.8.12.
  • Next, we have created a contract named StringCompare and within the contract, we created a function named Compare.
  • Now, this function takes two string variables named strVal1 and strVal2 as input and returns a boolean value.
  • After this, with the return statement, abi.encodePacked() is utilized to perform packed encoding on a string. And keccak256() helps to calculate the keccak256 hash of the encoding.
  • In the end, the bytes value of the hashes are compared and returns a boolean value.

Here is a sample execution of the above-created smart contract in Solidity.

Solidity String Comparison Example
Solidity String Comparison Example

Solidity String to bytes32

In this section, we will discuss how to convert a string data type variable in Solidity to a bytes32 value. Solidity facilitates the use of various flavors of byte data types for representing data in binary format. And one of these flavors is bytes32 which holds 32 bytes of data.

However, in Solidity, we cannot directly convert a string type value into the bytes32 value. For this implementation, we need to first convert the string value into bytes data type and from the bytes data type, we will convert it into bytes32.

The example for this implementation is given below.

 // SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.12;

contract StringTobytes32 {
    function StrTobytes32(string memory str) public pure returns (bytes32){
        
        return bytes32(bytes(str));

    } 
}

Again for the implementation, we are using the solidity version greater than 0.8.12. And initially, we created a contract named StringTobytes32 and within the contract, we created a function named StrTobytes32. Now, the StrTobytes32 function takes one string variable as input and returns its corresponding bytes32 value.

Solidity String to bytes32
Solidity String to bytes32

Here in the above execution, we are converting string value the “United States” to bytes32.

Solidity String to Address

On Ethereum, each smart contract and account is associated with an address which is a 20-byte value. Moreover, to execute a transaction on Ethereum, an address is required.

Solidity also facilitates the use of address type value in its smart contracts. And in this section, we will discuss how to convert a string type value to address.

However, in Solidity, we cannot directly convert a string type value into an address. For this task, first, we need to convert the string value into bytes then convert bytes into bytes20. In the last, we can convert the bytes20 type value into address.

Here is an example of this execution in Solidity.

 // SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.12;


contract StringToAddress {
    function StrToAddr(string memory str) public pure returns (address){
        
        return address(bytes20(bytes(str)));

    } 
}

In the above example, we are using solidity ^0.8.12 and we have created a contract named StringToAddress. Within the contract, we have created a function named StrToAddr. This function will simply take a string value as input and returns the corresponding address value.

Here is an execution sample where we have passed “Boston” as a string value and the contract returns its address value.

Solidity String to Address
Solidity String to Address

Solidity String Array

In this section, we will discuss how to create a string array in Solidity and we will also discuss an example for this implementation.

Just like other programming languages, Solidifty also has Arrays. So, Arrays in solidity are data structures that comprise a fixed set of data of the same data kinds, each with its index. Moreover, an array in Solidity can be either fixed or dynamic in size.

Here is a standard syntax of declaring a string type array in Solidity.

string <arr_name>[arr_size] = <arr_init>
  • In the above syntax, first, we need to define the data type of an array. So, for a string type array, we need to specify string first.
  • After this, in place of arr_name, we need to specify the name of the array. Next, we need to define the size of the array.
  • And in the end, if we want to initialize the array, we specify certain values in place of arr_init.
string[5] cities;       //fixed-size array
string[] cities;        //dynamic-sized array

In the above sample code, we have shown how to create fixed-size and dynamic-size arrays in Solidity.

Next, let’s understand how to create a string type array in Solidity using an example.

 // SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.12;

contract StringArray {
    string[] public cities;

    function getCities() public view returns (string[] memory) {
        return cities;
    }

    function pushToCities(string memory newCity) public {
        cities.push(newCity);
    }
}

Here in the above example, we created a contract named StringArray. In this contract, we declared a dynamic-sized public string type array named cities.

After this, we created a function named getCities which will return the values of the cities array. In the end, we created another function named pushToCities which helps to insert values in the cities string array.

Solidity String Array
Solidity String Array

In the above execution, first, we are using the pushToCities function to insert some values in the cities array. And then, we are using the getCities function to fetch the value of the cities array.

Solidity String Memory

The data in the Ethereum Virtual Machine (EVM) can be stored in 3 different ways. The first includes the use of Storage which is persistent in nature and it is quite expensive to use.

The second method includes the use of Memory which is a temporary form of storage and is wiped off for the next execution. However, using Memory is inexpensive as compared to Storage.

The third method includes the use of Stack. Even though a stack can be utilized to store a small amount of data, it can help in holding small local variables.

Now, in Solidity, we can use the STORAGE and MEMORY keywords to define the storage of the data. And we will focus on how to define a string variable in memory storage in Solidity. Generally, functions arguments in Solidity are mainly stored in memory. So, let’s understand the concept using an example.

 // SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.12;

contract StringName {
    string Name;

    function getName() public view returns (string memory) {
        return Name;
    }

    function setName(string memory P_Name) public {
        Name = P_Name;
    }
}
  • In the above example, we created a contract named StringName in Solidity.
  • After this, we defined a string type variable and also created 2 functions named getName and setName respectively.
  • The role of the getName function is to return the value of the Name variable which is of string memory type.
  • And the role of the setName function is to set the value of the Name variable by taking an input of string memory type.
Solidity String Memory
Solidity String Memory

In the above execution, first, we are using the setName function to set “Paul Walker” as a value in the Name variable. And then, we are using the getName function to fetch the value.

Solidity String to Uint256

In Solidity, a uint data type is utilized to store a positive integer value without any negative sign. Moreover, a uint data type in Solidity by default represents the uint256 type value with 256 bits.

String on the other hand in solidity can only be converted into bytes and we cannot convert bytes into uint. So, as of now, there is no efficient way in Solidity to convert a string value into uint256.

So, in this tutorial, we have discussed how to use the Solidity string data type with various examples in Solidity. Moreover, we have also illustrated the following set of topics.

  • Solidity string
  • Solidity string example
  • Solidity string concatenation
  • Solidity string length
  • Solidity string comparison
  • Solidity string to bytes32
  • Solidity string to address
  • Solidity string array
  • Solidity string memory
  • Solidity string to uint256