A string is a sequence of characters (like 'a', 'b', '!') that represents text. In GDScript, we write strings by wrapping text in either single quotes, double quotes, or triple double quotes. The following three examples are all equivalent:
var string_1 :="Hello, Godot!"var string_2 :='Hello, Godot!'var string_3 :="""Hello, Godot!"""
Strings can contain letters, numbers, symbols, and spaces: "Hello, Godot!", '250', and "@$%!" are all valid strings. Even an empty pair of quotes works: "" is called an empty string. It's an empty sequence of characters.We use strings for all our text needs in code:
Displaying a character's name
Dialogue lines
Error messages
And so on.
Common string operations
There are many operations you can perform on strings:
Joining: You can "add" two strings to append one to the other. "Hello " + "World" produces "Hello World".
Getting the length: You can call the length() method to get the number of characters in a string. "Hello".length() produces 5. You can use this to calculate the duration of a text appearance animation or how much space a text will take on the screen.
Replacing: You can call the replace() method to replace a substring with another. "Hodot".replace("H", "G") produces "Godot".
Capitalizing: You can call the capitalize() method to capitalize the first letter of a string. "godot".capitalize() produces "Godot".
There are many more operations that you can find by browsing the code reference in Godot: Go to Help -> Search Help... or press f1(on Mac:⌥space) on your keyboard.
When comparing strings using the equality operator (==), the computer checks if the strings match exactly, including uppercase and lowercase letters:
"hello" == "hello" is true
"Hello" == "hello" is false
If you need to compare strings ignoring case, most programming languages provide special methods. In Godot, you can call String.to_lower() to convert a string to lowercase before comparing it.
In some programming languages, there's a distinction between a single character and a string containing one character.For the computer, strings don't really exist: A string is an array of individual characters. In the C programming language, a language close to how the computer works, you could think of the string "Hello" like this: the array ['H', 'e', 'l', 'l', 'o', '\0'], where each value is a character. The last character, \0, is a special value that marks the end of the string. It's called the "null terminator."In GDScript, and in many modern languages, there isn't a separate character type. Instead, a single character is a string of length 1.