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 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;}}
Explanation
In the above code:
- Line 3: We create a contract
SolidityStrings. - Line 5: We declare string
str1using double quotesstring literal. - Line 8: We declare string
str2using a single quotestring literal. - Line 11: We declare string
str3usingstring constructor.
We also create the following getter functions:
- Line 14: We use
getString1()to retrieve the value ofstr1. - Line 19: We use
getString2()to retrieve the value ofstr2. - Line 24: We use
getString3()to retrieve the value ofstr3.