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.
string literal
string stringName = "value";
// or
string stringName = 'value';
string constructor
string stringName = new string(value);
Let’s see an example of Strings in Solidity:
pragma solidity ^0.5.0;contract SolidityStrings {// using double quotesstring str1 = "Edpresso";// using single quotesstring str2 = 'Educative';// using string constructorstring str3 = new string(2022);// getter function to retrieve value of str1function getString1() public view returns(string memory) {return str1;}// getter function to retrieve value of str2function getString2() public view returns(string memory) {return str2;}// getter function to retrieve value of str3function getString3() public view returns(string memory) {return str3;}}
In the above code:
SolidityStrings
.str1
using double quotes string literal
.str2
using a single quote string literal
.str3
using string constructor
.We also create the following getter functions:
getString1()
to retrieve the value of str1
.getString2()
to retrieve the value of str2
.getString3()
to retrieve the value of str3
.