What are Strings in Solidity?

Overview

Solidity provides a data type named string to declare variables of type String. It also extends support for string literals using single-quotes ' and double-quotes ".

A String can also be created using the string constructor.

Syntax

1. Using string literal

string stringName = "value";
// or
string stringName = 'value';

2. Using string constructor

string stringName = new string(value);

Code

Let’s see an example of Strings in Solidity:

pragma solidity ^0.5.0;
contract SolidityStrings {
// using double quotes
string str1 = "Edpresso";
// using single quotes
string str2 = 'Educative';
// using string constructor
string str3 = new string(2022);
// getter function to retrieve value of str1
function getString1() public view returns(string memory) {
return str1;
}
// getter function to retrieve value of str2
function getString2() public view returns(string memory) {
return str2;
}
// getter function to retrieve value of str3
function getString3() public view returns(string memory) {
return str3;
}
}

Explanation

In the above code:

  • Line 3: We create a contract SolidityStrings.
  • Line 5: We declare string str1 using double quotes string literal.
  • Line 8: We declare string str2 using a single quote string literal .
  • Line 11: We declare string str3 using string constructor.

We also create the following getter functions:

  • Line 14: We use getString1() to retrieve the value of str1.
  • Line 19: We use getString2() to retrieve the value of str2.
  • Line 24: We use getString3() to retrieve the value of str3.

Free Resources