Strings
Learn about strings in Solidity.
In Solidity, the string
keyword is used to specify the string data type. It represents and stores sequences of characters. The syntax of Solidity is influenced by languages like Python, C++, and JavaScript, incorporating their linguistic constructs. Here’s an example of a string in Solidity:
Note: String indexes start at 0, following the zero-based indexing convention commonly used in programming.
These strings are essentially dynamic arrays containing a mix of characters, which can range from alphabets and numbers to special symbols and spaces. Solidity stores data in strings using UTF-8 encoding. Both double quotes (" "
) and single quotes (' '
) can be used for string literals in Solidity, as follows:
// SPDX-License-Identifier: MITpragma solidity ^0.8.17;contract HelloWorld {// The greet variable is of type string with double quotes ("")string public greet = "Hello World!";// The welcome variable is of type string with single quotes ('')string public welcome = 'Hello World!';string public word;// Using a function to set the stringfunction setString() public {word = "hey";}// Using a function to update the string by taking a new string as a parameterfunction updateString(string memory _word) public {word = _word;}}
Line 4: We declare a contract named
HelloWorld
.Line 6: We introduce a public state variable named
greet
, categorized as thestring
type, and initialize it with the valueHello World!
using double quotes (""
).Line 8: We declare another public state variable named
welcome
. It’s also of typestring
and is initialized with the valueHello World!
using single quotes (''
).Line 10: We declare a public state variable named
word
, typed asstring
, without providing any initial value.Lines 13–15: We define a function named
setString()
with thepublic
visibility specifier. This function sets the value ...