Attention: Here be dragons

This is the latest (unstable) version of this documentation, which may document features not available in or compatible with released stable versions of Godot.

StringName

唯一字串內建型別。

說明

StringNames are immutable strings designed for general-purpose representation of unique names (also called "string interning"). Two StringNames with the same value are the same object. Comparing them is extremely fast compared to regular Strings.

You will usually pass a String to methods expecting a StringName and it will be automatically converted (often at compile time), but in rare cases you can construct a StringName ahead of time with the StringName constructor or, in GDScript, the literal syntax &"example". Manually constructing a StringName allows you to control when the conversion from String occurs or to use the literal and prevent conversions entirely.

See also NodePath, which is a similar concept specifically designed to store pre-parsed scene tree paths.

All of String's methods are available in this class too. They convert the StringName into a string, and they also return a string. This is highly inefficient and should only be used if the string is desired.

Note: In C#, an explicit conversion to System.String is required to use the methods listed on this page. Use the ToString() method to cast a StringName to a string, and then use the equivalent methods in System.String or StringExtensions.

Note: In a boolean context, a StringName will evaluate to false if it is empty (StringName("")). Otherwise, a StringName will always evaluate to true.

備註

使用 C# 操作此 API 時有顯著差異,詳見 C# API 與 GDScript 的不同

建構子

StringName

StringName()

StringName

StringName(from: StringName)

StringName

StringName(from: String)

方法

bool

begins_with(text: String) const

PackedStringArray

bigrams() const

int

bin_to_int() const

String

c_escape() const

String

c_unescape() const

String

capitalize() const

int

casecmp_to(to: String) const

bool

contains(what: String) const

bool

containsn(what: String) const

int

count(what: String, from: int = 0, to: int = 0) const

int

countn(what: String, from: int = 0, to: int = 0) const

String

dedent() const

bool

ends_with(text: String) const

String

erase(position: int, chars: int = 1) const

int

filecasecmp_to(to: String) const

int

filenocasecmp_to(to: String) const

int

find(what: String, from: int = 0) const

int

findn(what: String, from: int = 0) const

String

format(values: Variant, placeholder: String = "{_}") const

String

get_base_dir() const

String

get_basename() const

String

get_extension() const

String

get_file() const

String

get_slice(delimiter: String, slice: int) const

int

get_slice_count(delimiter: String) const

String

get_slicec(delimiter: int, slice: int) const

int

hash() const

PackedByteArray

hex_decode() const

int

hex_to_int() const

String

indent(prefix: String) const

String

insert(position: int, what: String) const

bool

is_absolute_path() const

bool

is_empty() const

bool

is_relative_path() const

bool

is_subsequence_of(text: String) const

bool

is_subsequence_ofn(text: String) const

bool

is_valid_ascii_identifier() const

bool

is_valid_filename() const

bool

is_valid_float() const

bool

is_valid_hex_number(with_prefix: bool = false) const

bool

is_valid_html_color() const

bool

is_valid_identifier() const

bool

is_valid_int() const

bool

is_valid_ip_address() const

bool

is_valid_unicode_identifier() const

String

join(parts: PackedStringArray) const

String

json_escape() const

String

left(length: int) const

int

length() const

String

lpad(min_length: int, character: String = " ") const

String

lstrip(chars: String) const

bool

match(expr: String) const

bool

matchn(expr: String) const

PackedByteArray

md5_buffer() const

String

md5_text() const

int

naturalcasecmp_to(to: String) const

int

naturalnocasecmp_to(to: String) const

int

nocasecmp_to(to: String) const

String

pad_decimals(digits: int) const

String

pad_zeros(digits: int) const

String

path_join(path: String) const

String

remove_char(what: int) const

String

remove_chars(chars: String) const

String

repeat(count: int) const

String

replace(what: String, forwhat: String) const

String

replace_char(key: int, with: int) const

String

replace_chars(keys: String, with: int) const

String

replacen(what: String, forwhat: String) const

String

reverse() const

int

rfind(what: String, from: int = -1) const

int

rfindn(what: String, from: int = -1) const

String

right(length: int) const

String

rpad(min_length: int, character: String = " ") const

PackedStringArray

rsplit(delimiter: String = "", allow_empty: bool = true, maxsplit: int = 0) const

String

rstrip(chars: String) const

PackedByteArray

sha1_buffer() const

String

sha1_text() const

PackedByteArray

sha256_buffer() const

String

sha256_text() const

float

similarity(text: String) const

String

simplify_path() const

PackedStringArray

split(delimiter: String = "", allow_empty: bool = true, maxsplit: int = 0) const

PackedFloat64Array

split_floats(delimiter: String, allow_empty: bool = true) const

String

strip_edges(left: bool = true, right: bool = true) const

String

strip_escapes() const

String

substr(from: int, len: int = -1) const

PackedByteArray

to_ascii_buffer() const

String

to_camel_case() const

float

to_float() const

int

to_int() const

String

to_kebab_case() const

String

to_lower() const

PackedByteArray

to_multibyte_char_buffer(encoding: String = "") const

String

to_pascal_case() const

String

to_snake_case() const

String

to_upper() const

PackedByteArray

to_utf8_buffer() const

PackedByteArray

to_utf16_buffer() const

PackedByteArray

to_utf32_buffer() const

PackedByteArray

to_wchar_buffer() const

String

trim_prefix(prefix: String) const

String

trim_suffix(suffix: String) const

int

unicode_at(at: int) const

String

uri_decode() const

String

uri_encode() const

String

uri_file_decode() const

String

validate_filename() const

String

validate_node_name() const

String

xml_escape(escape_quotes: bool = false) const

String

xml_unescape() const

運算子

bool

operator !=(right: String)

bool

operator !=(right: StringName)

String

operator %(right: Variant)

String

operator +(right: String)

String

operator +(right: StringName)

bool

operator <(right: StringName)

bool

operator <=(right: StringName)

bool

operator ==(right: String)

bool

operator ==(right: StringName)

bool

operator >(right: StringName)

bool

operator >=(right: StringName)


建構子說明

StringName StringName() 🔗

建構空的 StringName


StringName StringName(from: StringName)

建構給定 StringName 的副本。


StringName StringName(from: String)

從給定的 String 建立 StringName。在 GDScript 中,StringName("example")&"example" 等價。


方法說明

bool begins_with(text: String) const 🔗

如果該字串以給定的 text 開始,則返回 true。另見 ends_with()


PackedStringArray bigrams() const 🔗

返回包含該字串的雙字母組(連續字母的組合)的陣列。

print("Get up!".bigrams()) # 輸出 ["Ge", "et", "t ", " u", "up", "p!"]

int bin_to_int() const 🔗

將表示二進位數字的字串轉換為 int。該字串可以前綴 "0b",負數可以前綴 -

print("101".bin_to_int())   # 輸出 5
print("0b101".bin_to_int()) # 輸出 5
print("-0b10".bin_to_int()) # 輸出 -2

String c_escape() const 🔗

返回該字串的副本,按照 C 語言標準對特殊字元進行轉義。


String c_unescape() const 🔗

返回該字串的副本,轉義字元均使用本義代替。支援的轉義序列有 \'\"\\\a\b\f\n\r\t\v

注意:與 GDScript 解析器不同,這個方法不支援 \uXXXX 轉義序列。


String capitalize() const 🔗

改變字串的外觀:將底線 (_) 取代為空格,在單字中間的大寫字母前新增空格,將所有字母轉換為小寫,然後將第一個字母以及每個在空格之後的字母轉換為大寫。

"move_local_x".capitalize()   # Returns "Move Local X"
"sceneFile_path".capitalize() # Returns "Scene File Path"
"2D, FPS, PNG".capitalize()   # Returns "2d, Fps, Png"

int casecmp_to(to: String) const 🔗

Performs a case-sensitive comparison to another string. Returns -1 if less than, 1 if greater than, or 0 if equal. "Less than" and "greater than" are determined by the Unicode code points of each string, which roughly matches the alphabetical order.

With different string lengths, returns 1 if this string is longer than the to string, or -1 if shorter. Note that the length of empty strings is always 0.

To get a bool result from a string comparison, use the == operator instead. See also nocasecmp_to(), filecasecmp_to(), and naturalcasecmp_to().


bool contains(what: String) const 🔗

Returns true if the string contains what. In GDScript, this corresponds to the in operator.

print("Node".contains("de")) # Prints true
print("team".contains("I"))  # Prints false
print("I" in "team")         # Prints false

If you need to know where what is within the string, use find(). See also containsn().


bool containsn(what: String) const 🔗

Returns true if the string contains what, ignoring case.

If you need to know where what is within the string, use findn(). See also contains().


int count(what: String, from: int = 0, to: int = 0) const 🔗

返回子串 whatfromto 位置之間出現的次數。如果 to 為 0,會在剩餘字串中繼續搜索。


int countn(what: String, from: int = 0, to: int = 0) const 🔗

返回子串 whatfromto 位置之間出現的次數,忽略大小寫。如果 to 為 0,會在剩餘字串中繼續搜索。


String dedent() const 🔗

返回刪除了縮進(前導定位字元和空格)的字串副本。新增縮進請參閱 indent()


bool ends_with(text: String) const 🔗

如果該字串以給定的 text 結束,則返回 true。另見 begins_with()


String erase(position: int, chars: int = 1) const 🔗

返回從 position 開始擦除 chars 個字元後的字串。如果在指定 position 的基礎上 chars 超過字串的長度,返回的字串中擦除的字元數會少於請求的數量。如果 positionchars 為負數,則返回空字串。如果 chars0 則返回原字串,不進行修改。


int filecasecmp_to(to: String) const 🔗

Like naturalcasecmp_to() but prioritizes strings that begin with periods (.) and underscores (_) before any other character. Useful when sorting folders or file names.

To get a bool result from a string comparison, use the == operator instead. See also filenocasecmp_to(), naturalcasecmp_to(), and casecmp_to().


int filenocasecmp_to(to: String) const 🔗

Like naturalnocasecmp_to() but prioritizes strings that begin with periods (.) and underscores (_) before any other character. Useful when sorting folders or file names.

To get a bool result from a string comparison, use the == operator instead. See also filecasecmp_to(), naturalnocasecmp_to(), and nocasecmp_to().


int find(what: String, from: int = 0) const 🔗

Returns the index of the first occurrence of what in this string, or -1 if there are none. The search's start can be specified with from, continuing to the end of the string.

print("Team".find("I")) # Prints -1

print("Potato".find("t"))    # Prints 2
print("Potato".find("t", 3)) # Prints 4
print("Potato".find("t", 5)) # Prints -1

Note: If you just want to know whether the string contains what, use contains(). In GDScript, you may also use the in operator.

Note: A negative value of from is converted to a starting index by counting back from the last possible index with enough space to find what.


int findn(what: String, from: int = 0) const 🔗

返回這個字串中 what 首次出現的索引,不區分大小寫,不存在時則為 -1。搜索的起點可以用 from 指定,終點為該字元串的末尾。


String format(values: Variant, placeholder: String = "{_}") const 🔗

Formats the string by replacing all occurrences of placeholder with the elements of values.

values can be a Dictionary, an Array, or an Object. Any underscores in placeholder will be replaced with the corresponding keys in advance. Array elements use their index as keys.

# Prints "Waiting for Godot is a play by Samuel Beckett, and Godot Engine is named after it."
var use_array_values = "Waiting for {0} is a play by {1}, and {0} Engine is named after it."
print(use_array_values.format(["Godot", "Samuel Beckett"]))

# Prints "User 42 is Godot."
print("User {id} is {name}.".format({"id": 42, "name": "Godot"}))

Some additional handling is performed when values is an Array. If placeholder does not contain an underscore, the elements of the values array will be used to replace one occurrence of the placeholder in order; If an element of values is another 2-element array, it'll be interpreted as a key-value pair.

# Prints "User 42 is Godot."
print("User {} is {}.".format([42, "Godot"], "{}"))
print("User {id} is {name}.".format([["id", 42], ["name", "Godot"]]))

When passing an Object, the property names from Object.get_property_list() are used as keys.

# Prints "Visible true, position (0, 0)"
var node = Node2D.new()
print("Visible {visible}, position {position}".format(node))

See also the GDScript format string tutorial.

Note: Each replacement is done sequentially for each element of values, not all at once. This means that if any element is inserted and it contains another placeholder, it may be changed by the next replacement. While this can be very useful, it often causes unexpected results. If not necessary, make sure values's elements do not contain placeholders.

print("{0} {1}".format(["{1}", "x"]))           # Prints "x x"
print("{0} {1}".format(["x", "{0}"]))           # Prints "x {0}"
print("{a} {b}".format({"a": "{b}", "b": "c"})) # Prints "c c"
print("{a} {b}".format({"b": "c", "a": "{b}"})) # Prints "{b} c"

Note: In C#, it's recommended to interpolate strings with "$", instead.


String get_base_dir() const 🔗

如果該字串是有效的檔路徑,則返回基礎目錄名稱。

var dir_path = "/path/to/file.txt".get_base_dir() # dir_path 為 "/path/to"

String get_basename() const 🔗

如果該字串是有效的檔路徑,則返回完整檔路徑,不包括副檔名。

var base = "/path/to/file.txt".get_basename() # base 為 "/path/to/file"

String get_extension() const 🔗

如果該字串是有效的檔案名或路徑,則返回該檔的副檔名,不含開頭的點號(.)。否則返回空字串。

var a = "/path/to/file.txt".get_extension() # a 為 "txt"
var b = "cool.txt".get_extension()          # b 為 "txt"
var c = "cool.font.tres".get_extension()    # c 為 "tres"
var d = ".pack1".get_extension()            # d 為 "pack1"

var e = "file.txt.".get_extension()  # e 為 ""
var f = "file.txt..".get_extension() # f 為 ""
var g = "txt".get_extension()        # g 為 ""
var h = "".get_extension()           # h 為 ""

String get_file() const 🔗

如果該字串是有效的檔路徑,則返回呼函式案名,包括副檔名。

var file = "/path/to/icon.png".get_file() # file 為 "icon.png"

String get_slice(delimiter: String, slice: int) const 🔗

Splits the string using a delimiter and returns the substring at index slice. Returns the original string if delimiter does not occur in the string. Returns an empty string if the slice does not exist.

This is faster than split(), if you only need one substring.

print("i/am/example/hi".get_slice("/", 2)) # Prints "example"

int get_slice_count(delimiter: String) const 🔗

返回使用給定的分隔符號 delimiter 拆分該字串後切片的總數(見 split())。


String get_slicec(delimiter: int, slice: int) const 🔗

使用 Unicode 字元碼分隔符號 delimiter 拆分該字串,返回索引為 slice 的子串。如果 slice 不存在則返回空字串。

只需要一個子串時這個方法比 split() 快。


int hash() const 🔗

Returns the 32-bit hash value representing the string's contents.

Note: Strings with equal hash values are not guaranteed to be the same, as a result of hash collisions. On the contrary, strings with different hash values are guaranteed to be different.


PackedByteArray hex_decode() const 🔗

Decodes a hexadecimal string as a PackedByteArray.

var text = "hello world"
var encoded = text.to_utf8_buffer().hex_encode() # outputs "68656c6c6f20776f726c64"
print(encoded.hex_decode().get_string_from_utf8())

int hex_to_int() const 🔗

將表示十六進位數的字串轉換為 int。該字串可以前綴 "0x",負數可以前綴 -

print("0xff".hex_to_int()) # 輸出 255
print("ab".hex_to_int())   # 輸出 171

String indent(prefix: String) const 🔗

使用前綴 prefix 將該字串中的每一行進行縮進。空行不縮進。移除縮進請參閱 dedent()

例如,該字串可以用 "\t\t" 縮進兩個定位停駐點,用 "    " 縮進四個空格。


String insert(position: int, what: String) const 🔗

在該字串中的 position 位置插入 what


bool is_absolute_path() const 🔗

如果該字串為檔或目錄的路徑,並且明確的指定了起點,則返回 true。這個方法與 is_relative_path() 相反。

包括以 "res://""user://""C:\""/" 等開頭的路徑。


bool is_empty() const 🔗

如果該字串的長度為 0""),則返回 true。另見 length()


bool is_relative_path() const 🔗

如果該字串為檔或目錄的路徑,並且起點依賴於本文,則返回 true。路徑可以是從目前的目錄開始,也可以是從目前 Node 開始(如果該字串是從 NodePath 得到的),有時候也可以是使用了 "./" 前綴。這個方法與 is_absolute_path() 相反。


bool is_subsequence_of(text: String) const 🔗

Returns true if all characters of this string can be found in text in their original order. This is not the same as contains().

var text = "Wow, incredible!"

print("inedible".is_subsequence_of(text)) # Prints true
print("Word!".is_subsequence_of(text))    # Prints true
print("Window".is_subsequence_of(text))   # Prints false
print("".is_subsequence_of(text))         # Prints true

bool is_subsequence_ofn(text: String) const 🔗

Returns true if all characters of this string can be found in text in their original order, ignoring case. This is not the same as containsn().


bool is_valid_ascii_identifier() const 🔗

Returns true if this string is a valid ASCII identifier. A valid ASCII identifier may contain only letters, digits, and underscores (_), and the first character may not be a digit.

print("node_2d".is_valid_ascii_identifier())    # Prints true
print("TYPE_FLOAT".is_valid_ascii_identifier()) # Prints true
print("1st_method".is_valid_ascii_identifier()) # Prints false
print("MyMethod#2".is_valid_ascii_identifier()) # Prints false

See also is_valid_unicode_identifier().


bool is_valid_filename() const 🔗

Returns true if this string is a valid file name. A valid file name cannot be empty, begin or end with space characters, or contain characters that are not allowed (: / \ ? * " | % < >).


bool is_valid_float() const 🔗

如果該字串代表有效的浮點數,則返回 true。浮點數只能包含數位、一個小數點(.)以及指數字元(e)。還可以前綴正號(+)或負號(-)。有效的整數同時也是有效的浮點數(見 is_valid_int())。另見 to_float()

print("1.7".is_valid_float())   # 輸出 true
print("24".is_valid_float())    # 輸出 true
print("7e3".is_valid_float())   # 輸出 true
print("Hello".is_valid_float()) # 輸出 false

bool is_valid_hex_number(with_prefix: bool = false) const 🔗

如果該字串代表有效的十六進位數,則返回 true。有效的十六進位數只能包含數位或字母 AF(大小寫均可),還可以前綴正號(+)或負號(-)。

如果 with_prefixtrue,則十六進位數需要有 "0x" 前綴才算有效。

print("A08E".is_valid_hex_number())    # 輸出 true
print("-AbCdEf".is_valid_hex_number()) # 輸出 true
print("2.5".is_valid_hex_number())     # 輸出 false

print("0xDEADC0DE".is_valid_hex_number(true)) # 輸出 true

bool is_valid_html_color() const 🔗

如果該字串是有效的十六進位 HTML 顏色標記,則返回 true。該字元串必須為 3 位、4 位、6 位或 8 位元字元的十六進位值(見 is_valid_hex_number()),也可以帶有井號前綴(#)。名稱、hsl() 等其他 HTML 顏色標記法無效。另見 Color.html()


bool is_valid_identifier() const 🔗

已棄用: Use is_valid_ascii_identifier() instead.

如果該字串為有效的識別字,則返回 true。有效的識別字僅可以包含字母、數位和底線(_),第一個字元不能為數位。

print("node_2d".is_valid_identifier())    # 輸出 true
print("TYPE_FLOAT".is_valid_identifier()) # 輸出 true
print("1st_method".is_valid_identifier()) # 輸出 false
print("MyMethod#2".is_valid_identifier()) # 輸出 false

bool is_valid_int() const 🔗

如果該字串代表有效的整數,則返回 true。有效的整數僅可以包含數字,還可以前綴正號(+)或負號(-)。另見 to_int()

print("7".is_valid_int())    # 輸出 true
print("1.65".is_valid_int()) # 輸出 false
print("Hi".is_valid_int())   # 輸出 false
print("+3".is_valid_int())   # 輸出 true
print("-12".is_valid_int())  # 輸出 true

bool is_valid_ip_address() const 🔗

如果該字串表示格式正確的 IPv4 或 IPv6 位址,則返回 true。這個方法認為 0.0.0.0"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"保留 IP 位址是有效的。


bool is_valid_unicode_identifier() const 🔗

Returns true if this string is a valid Unicode identifier.

A valid Unicode identifier must begin with a Unicode character of class XID_Start or "_", and may contain Unicode characters of class XID_Continue in the other positions.

print("node_2d".is_valid_unicode_identifier())      # Prints true
print("1st_method".is_valid_unicode_identifier())   # Prints false
print("MyMethod#2".is_valid_unicode_identifier())   # Prints false
print("állóképesség".is_valid_unicode_identifier()) # Prints true
print("выносливость".is_valid_unicode_identifier()) # Prints true
print("体力".is_valid_unicode_identifier())         # Prints true

See also is_valid_ascii_identifier().

Note: This method checks identifiers the same way as GDScript. See TextServer.is_valid_identifier() for more advanced checks.


String join(parts: PackedStringArray) const 🔗

Returns the concatenation of parts' elements, with each element separated by the string calling this method. This method is the opposite of split().

var fruits = ["Apple", "Orange", "Pear", "Kiwi"]

print(", ".join(fruits))  # Prints "Apple, Orange, Pear, Kiwi"
print("---".join(fruits)) # Prints "Apple---Orange---Pear---Kiwi"

String json_escape() const 🔗

返回該字串的副本,使用 JSON 標準對特殊字元進行轉義。因為與 C 標準非常類似,所以需要時可以用 c_unescape() 取消轉義。


String left(length: int) const 🔗

返回該字串開頭的前 length 個字元。如果 length 為負,則會從該字串的末尾剝離最後 length 個字元。

print("Hello World!".left(3))  # 輸出 "Hel"
print("Hello World!".left(-4)) # 輸出 "Hello Wo"

int length() const 🔗

返回該字串中的字元數。空字串("")始終返回 0。另見 is_empty()


String lpad(min_length: int, character: String = " ") const 🔗

必要時在該字串的左側新增若干 character 字元,使其長度至少為 min_length。另見 rpad()


String lstrip(chars: String) const 🔗

從該字串的開頭移除 chars 中定義的字元。另見 rstrip()

注意:chars 不是前綴。如果要移除前綴而不是一組字元,請使用 trim_prefix()


bool match(expr: String) const 🔗

進行簡單的運算式配對(也叫“通配”),* 配對零個或多個任意字元,? 配對除英文句號外的任意字元(.)。使用空字串或空運算式時始終為 false


bool matchn(expr: String) const 🔗

進行簡單的大小寫不敏感運算式配對(也叫“通配”),* 配對零個或多個任意字元,? 配對除英文句號外的任意字元(.)。使用空字串或空運算式時始終為 false


PackedByteArray md5_buffer() const 🔗

返回該字串的 MD5 雜湊,型別為 PackedByteArray


String md5_text() const 🔗

返回該字串的 MD5 雜湊,型別 String


int naturalcasecmp_to(to: String) const 🔗

Performs a case-sensitive, natural order comparison to another string. Returns -1 if less than, 1 if greater than, or 0 if equal. "Less than" or "greater than" are determined by the Unicode code points of each string, which roughly matches the alphabetical order.

When used for sorting, natural order comparison orders sequences of numbers by the combined value of each digit as is often expected, instead of the single digit's value. A sorted sequence of numbered strings will be ["1", "2", "3", ...], not ["1", "10", "2", "3", ...].

With different string lengths, returns 1 if this string is longer than the to string, or -1 if shorter. Note that the length of empty strings is always 0.

To get a bool result from a string comparison, use the == operator instead. See also naturalnocasecmp_to(), filecasecmp_to(), and nocasecmp_to().


int naturalnocasecmp_to(to: String) const 🔗

Performs a case-insensitive, natural order comparison to another string. Returns -1 if less than, 1 if greater than, or 0 if equal. "Less than" or "greater than" are determined by the Unicode code points of each string, which roughly matches the alphabetical order. Internally, lowercase characters are converted to uppercase for the comparison.

When used for sorting, natural order comparison orders sequences of numbers by the combined value of each digit as is often expected, instead of the single digit's value. A sorted sequence of numbered strings will be ["1", "2", "3", ...], not ["1", "10", "2", "3", ...].

With different string lengths, returns 1 if this string is longer than the to string, or -1 if shorter. Note that the length of empty strings is always 0.

To get a bool result from a string comparison, use the == operator instead. See also naturalcasecmp_to(), filenocasecmp_to(), and casecmp_to().


int nocasecmp_to(to: String) const 🔗

Performs a case-insensitive comparison to another string. Returns -1 if less than, 1 if greater than, or 0 if equal. "Less than" or "greater than" are determined by the Unicode code points of each string, which roughly matches the alphabetical order. Internally, lowercase characters are converted to uppercase for the comparison.

With different string lengths, returns 1 if this string is longer than the to string, or -1 if shorter. Note that the length of empty strings is always 0.

To get a bool result from a string comparison, use the == operator instead. See also casecmp_to(), filenocasecmp_to(), and naturalnocasecmp_to().


String pad_decimals(digits: int) const 🔗

格式化表示數位的字串,使其小數點的位數為 digits


String pad_zeros(digits: int) const 🔗

格式化表示數位的字串,使其小數點的位數為 digits


String path_join(path: String) const 🔗

Concatenates path at the end of the string as a subpath, adding / if necessary.

Example: "this/is".path_join("path") == "this/is/path".


String remove_char(what: int) const 🔗

Removes all occurrences of the Unicode character with code what. Faster version of replace() when the key is only one character long and the replacement is "".


String remove_chars(chars: String) const 🔗

Removes all occurrences of the characters in chars. See also remove_char().


String repeat(count: int) const 🔗

將該字串重複若干次。次數 count 需要大於0 。否則返回空字串。


String replace(what: String, forwhat: String) const 🔗

將該字串中出現的所有 what 都替換為給定的 forwhat


String replace_char(key: int, with: int) const 🔗

Replaces all occurrences of the Unicode character with code key with the Unicode character with code with. Faster version of replace() when the key is only one character long. To get a single character use "X".unicode_at(0) (note that some strings, like compound letters and emoji, can be composed of multiple unicode codepoints, and will not work with this method, use length() to make sure).


String replace_chars(keys: String, with: int) const 🔗

Replaces any occurrence of the characters in keys with the Unicode character with code with. See also replace_char().


String replacen(what: String, forwhat: String) const 🔗

將該字串中出現的所有 what 都替換為給定的 forwhat大小寫不敏感


String reverse() const 🔗

Returns the copy of this string in reverse order. This operation works on unicode codepoints, rather than sequences of codepoints, and may break things like compound letters or emojis.


int rfind(what: String, from: int = -1) const 🔗

Returns the index of the last occurrence of what in this string, or -1 if there are none. The search's start can be specified with from, continuing to the beginning of the string. This method is the reverse of find().

Note: A negative value of from is converted to a starting index by counting back from the last possible index with enough space to find what.

Note: A value of from that is greater than the last possible index with enough space to find what is considered out-of-bounds, and returns -1.


int rfindn(what: String, from: int = -1) const 🔗

返回這個字串中 what 最後一次出現時的索引,不區分大小寫,不存在時則為 -1。搜索的起點可以用 from 指定,終點為該字串的末尾。這個方法與 findn() 相對。


String right(length: int) const 🔗

返回該字串末尾的最後 length 個字元。如果 length 為負,則會從該字串的開頭剝離前 length 個字元。

print("Hello World!".right(3))  # 輸出 "ld!"
print("Hello World!".right(-4)) # 輸出 "o World!"

String rpad(min_length: int, character: String = " ") const 🔗

必要時在該字串的右側新增若干 character 字元,使其長度至少為 min_length。另見 lpad()


PackedStringArray rsplit(delimiter: String = "", allow_empty: bool = true, maxsplit: int = 0) const 🔗

Splits the string using a delimiter and returns an array of the substrings, starting from the end of the string. The splits in the returned array appear in the same order as the original string. If delimiter is an empty string, each substring will be a single character.

If allow_empty is false, empty strings between adjacent delimiters are excluded from the array.

If maxsplit is greater than 0, the number of splits may not exceed maxsplit. By default, the entire string is split, which is mostly identical to split().

var some_string = "One,Two,Three,Four"
var some_array = some_string.rsplit(",", true, 1)

print(some_array.size()) # Prints 2
print(some_array[0])     # Prints "One,Two,Three"
print(some_array[1])     # Prints "Four"

String rstrip(chars: String) const 🔗

從該字串的結尾移除 chars 中定義的字元。另見 rstrip()

注意:chars 不是後綴。如果要移除後綴而不是一組字元,請使用 trim_suffix()


PackedByteArray sha1_buffer() const 🔗

返回該字串的 SHA-1 雜湊,類型為 PackedByteArray


String sha1_text() const 🔗

返回該字串的 SHA-1 雜湊,類型為 String


PackedByteArray sha256_buffer() const 🔗

返回該字串的 SHA-256 雜湊,型別為 PackedByteArray


String sha256_text() const 🔗

返回該字串的 SHA-256 雜湊,型別為 String


float similarity(text: String) const 🔗

Returns the similarity index (Sørensen-Dice coefficient) of this string compared to another. A result of 1.0 means totally similar, while 0.0 means totally dissimilar.

print("ABC123".similarity("ABC123")) # Prints 1.0
print("ABC123".similarity("XYZ456")) # Prints 0.0
print("ABC123".similarity("123ABC")) # Prints 0.8
print("ABC123".similarity("abc123")) # Prints 0.4

String simplify_path() const 🔗

如果該字串為有效的檔路徑,則將其轉換為規範路徑。規範路徑是最短路徑,不帶 "./" 和所有不必要的 "..""/"

var simple_path = "./path/to///../file".simplify_path()
print(simple_path) # 輸出 "path/file"

PackedStringArray split(delimiter: String = "", allow_empty: bool = true, maxsplit: int = 0) const 🔗

Splits the string using a delimiter and returns an array of the substrings. If delimiter is an empty string, each substring will be a single character. This method is the opposite of join().

If allow_empty is false, empty strings between adjacent delimiters are excluded from the array.

If maxsplit is greater than 0, the number of splits may not exceed maxsplit. By default, the entire string is split.

var some_array = "One,Two,Three,Four".split(",", true, 2)

print(some_array.size()) # Prints 3
print(some_array[0])     # Prints "One"
print(some_array[1])     # Prints "Two"
print(some_array[2])     # Prints "Three,Four"

Note: If you only need one substring from the array, consider using get_slice() which is faster. If you need to split strings with more complex rules, use the RegEx class instead.


PackedFloat64Array split_floats(delimiter: String, allow_empty: bool = true) const 🔗

使用分隔符號 delimiter 將該字串拆分為浮點數,返回 PackedFloat64Array

如果 allow_emptyfalse,則會排除相鄰分隔符號之間為空或無法轉換為 float 的內容。

var a = "1,2,4.5".split_floats(",")         # a 為 [1.0, 2.0, 4.5]
var c = "1| ||4.5".split_floats("|")        # c 為 [1.0, 0.0, 0.0, 4.5]
var b = "1| ||4.5".split_floats("|", false) # b 為 [1.0, 4.5]

String strip_edges(left: bool = true, right: bool = true) const 🔗

從該字串的開頭和結尾剝離所有不可列印的字元。其中包括空格、定位字元(\t)以及分行符號(\n \r)。

如果 leftfalse,會忽略該字串的開頭。與此類似,如果 rightfalse,則會忽略該字串的結尾。


String strip_escapes() const 🔗

從該字串中剝離所有轉義字元。其中包括 ASCII 表第一頁的所有不可列印控制字元(值為 0 到 32),例如定位字元(C 中的 \t)和分行符號(\n]\r) 字元,但不包括空格。


String substr(from: int, len: int = -1) const 🔗

返回該字串中的某一部分,位置從 from 開始,長度為 len。如果 len-1(預設值),將返回開給定位置開始的剩餘字元。


PackedByteArray to_ascii_buffer() const 🔗

將該字串轉換為 ASCII/Latin-1 編碼的 PackedByteArray。這個方法比 to_utf8_buffer() 稍快,但會把不支援的字元都替換為空格。


String to_camel_case() const 🔗

返回將該字串轉換為小駝峰命名 camelCase 的結果。


float to_float() const 🔗

將代表十進位數字的字串轉換為 float。該方法會在首個非數位字元處停止,除非是首次遇到 .(小數點)以及表示指數的 e。另見 is_valid_float()

var a = "12.35".to_float() # a 為 12.35
var b = "1.2.3".to_float() # b 為 1.2
var c = "12xy3".to_float() # c 為 12.0
var d = "1e3".to_float()   # d 為 1000.0
var e = "Hello!".to_float()  # e 為 0.0

int to_int() const 🔗

將代表整數的字串轉換為 int。該方法會刪除所有非數位字元,並在遇到 . 後停止。另見 is_valid_int()

var a = "123".to_int()    # a 為 123
var b = "x1y2z3".to_int() # b 為 123
var c = "-1.2.3".to_int() # c 為 -1
var d = "Hello!".to_int() # d 為 0

String to_kebab_case() const 🔗

Returns the string converted to kebab-case.

Note: Numbers followed by a single letter are not separated in the conversion to keep some words (such as "2D") together.

"Node2D".to_kebab_case()               # Returns "node-2d"
"2nd place".to_kebab_case()            # Returns "2-nd-place"
"Texture3DAssetFolder".to_kebab_case() # Returns "texture-3d-asset-folder"

String to_lower() const 🔗

Returns the string converted to lowercase.


PackedByteArray to_multibyte_char_buffer(encoding: String = "") const 🔗

Converts the string to system multibyte code page encoded PackedByteArray. If conversion fails, empty array is returned.

The values permitted for encoding are system dependent. If encoding is empty string, system default encoding is used.

  • For Windows, see Code Page Identifiers .NET names.

  • For macOS and Linux/BSD, see libiconv library documentation and iconv --list for a list of supported encodings.


String to_pascal_case() const 🔗

返回將該字串轉換為大駝峰命名 PascalCase 的結果。


String to_snake_case() const 🔗

Returns the string converted to snake_case.

Note: Numbers followed by a single letter are not separated in the conversion to keep some words (such as "2D") together.

"Node2D".to_snake_case()               # Returns "node_2d"
"2nd place".to_snake_case()            # Returns "2_nd_place"
"Texture3DAssetFolder".to_snake_case() # Returns "texture_3d_asset_folder"

String to_upper() const 🔗

Returns the string converted to UPPERCASE.


PackedByteArray to_utf8_buffer() const 🔗

將該字串轉換為 UTF-8 編碼的 PackedByteArray。這個方法比 to_ascii_buffer() 稍慢,但支援所有 UTF-8 字元。大多數情況下請優先使用這個方法。


PackedByteArray to_utf16_buffer() const 🔗

將該字串轉換為 UTF-16 編碼的 PackedByteArray


PackedByteArray to_utf32_buffer() const 🔗

將該字串轉換為 UTF-32 編碼的 PackedByteArray


PackedByteArray to_wchar_buffer() const 🔗

將該字串轉換為 寬字元wchat_t,Windows 上為 UTF-16,其他平臺上為 UTF-32)編碼的 PackedByteArray


String trim_prefix(prefix: String) const 🔗

移除該字串開頭的 prefix 前綴,否則原樣返回該字串。


String trim_suffix(suffix: String) const 🔗

移除該字串末尾的 suffix 後綴,否則原樣返回該字串。


int unicode_at(at: int) const 🔗

Returns the character code at position at.

See also String.chr(), @GDScript.char(), and @GDScript.ord().


String uri_decode() const 🔗

Decodes the string from its URL-encoded format. This method is meant to properly decode the parameters in a URL when receiving an HTTP request. See also uri_encode().

var url = "$DOCS_URL/?highlight=Godot%20Engine%3%docs"
print(url.uri_decode()) # Prints "$DOCS_URL/?highlight=Godot Engine:docs"

Note: This method decodes + as space.


String uri_encode() const 🔗

將該字串按照對 URL 友好的格式進行編碼。該方法的目的是在發送 HTTP 請求時,正確編碼 URL 中的參數。另見 uri_decode()

var prefix = "$DOCS_URL/?highlight="
var url = prefix + "Godot Engine:docs".uri_encode()

print(url) # 輸出 "$DOCS_URL/?highlight=Godot%20Engine%3%docs"

String uri_file_decode() const 🔗

Decodes the file path from its URL-encoded format. Unlike uri_decode() this method leaves + as is.


String validate_filename() const 🔗

返回該字串的副本,所有 is_valid_filename() 中不允許的字元都會被替換為底線。


String validate_node_name() const 🔗

返回該字串的副本,所有 Node.name 中不允許的字元都會被替換為底線(. : @ / " %))。


String xml_escape(escape_quotes: bool = false) const 🔗

返回該字串的副本,使用 XML 標準對特殊字元進行轉義。如果 escape_quotestrue,則單引號(')和雙引號(")字元也會被轉義。


String xml_unescape() const 🔗

返回該字串的副本,轉義字元均按照 XML 標準使用本義代替。


運算子說明

bool operator !=(right: String) 🔗

如果該 StringName 與給定的 String 不等價,則返回 true


bool operator !=(right: StringName) 🔗

如果該 StringNameright 不指向同一個名稱,則返回 trueStringName 間的比較比常規 String 間的比較要快很多。


String operator %(right: Variant) 🔗

格式化該 StringName,使用若干參數替換預留位置,返回的是 String。要傳遞多個參數時,right 應為 Array

更多資訊見《GDScript 格式字串》教學。

注意:C# 中沒有等價的運算子。見如何使用“$”插入字串


String operator +(right: String) 🔗

right 追加到該 StringName 的末尾,返回的是 String。也稱作字元串連接。


String operator +(right: StringName) 🔗

right 追加到該 StringName 的末尾,返回的是 String。也稱作字元串連接。


bool operator <(right: StringName) 🔗

如果左側的 StringName 的指針比 right 靠前,則返回 true。注意,這與 Unicode 順序是不同的。


bool operator <=(right: StringName) 🔗

如果左側的 StringName 的指針比 right 靠前或者相同,則返回 true。注意,這與 Unicode 順序是不同的。


bool operator ==(right: String) 🔗

如果該 StringName 與給定的 String 等價,則返回 true


bool operator ==(right: StringName) 🔗

如果該 StringNameright 指向同一個名稱,則返回 trueStringName 間的比較比常規 String 間的比較要快很多。


bool operator >(right: StringName) 🔗

如果左側的 StringName 的指針比 right 靠後,則返回 true。注意,這與 Unicode 順序是不同的。


bool operator >=(right: StringName) 🔗

如果左側的 StringName 的指針比 right 靠後或相同,則返回 true。注意,這與 Unicode 順序是不同的。