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:

Press + to interact
Solidity string example with zero-based indexing
Solidity string example with zero-based indexing

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:

Press + to interact
// SPDX-License-Identifier: MIT
pragma 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 string
function setString() public {
word = "hey";
}
// Using a function to update the string by taking a new string as a parameter
function 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 the string type, and initialize it with the value Hello World! using double quotes ("").

  • Line 8: We declare another public state variable named welcome. It’s also of type string and is initialized with the value Hello World! using single quotes ('').

  • Line 10: We declare a public state variable named word, typed as string, without providing any initial value.

  • Lines 13–15: We define a function named setString() with the public visibility specifier. This function sets the value ...