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

唯一字串內建型別。

說明

StringName 是不可變的字串,用於唯一名稱的通用表示(也叫“字串內嵌”)。值相同的兩個 StringName 是同一個物件。進行比較時比普通 String 要快很多。

需要 StringName 的方法通常可以傳 String,會自動進行轉換(經常發生在編譯時),不過有時候你可能會想要提前使用 StringName 建構函式來構造 StringName,在 GDScript 中也可以用字面量語法 &"example"。你可以通過手動構造 StringName 來控制 String 的轉換時機,使用字面量則可以完全消除掉轉換過程。

另見 NodePath,這是與此類似的概念,針對儲存預解析的場景樹路徑設計。

String 的所有方法都在這個類中可用。它們會將 StringName 轉換為字串,回傳的也是字串。這樣做效率非常低,應該只在需要字串時使用。

注意:在 C# 中,需要顯式轉換為 System.String 才能使用本頁列出的方法。使用 ToString() 方法將 StringName 轉換為字串,然後使用 System.String 或 StringExtensions 中的等效方法。

注意:轉換為布林值時,空的 StringName(StringName(""))為 false,其他 StringName 均為 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 🔗

Returns a copy of the string with escaped characters replaced by their meanings. Supported escape sequences are \', \", \\, \a, \b, \f, \n, \r, \t, \v.

Note: Unlike the GDScript parser, this method doesn't support the \uXXXX escape sequence.


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 🔗

與另一個字串進行區分大小寫的比較。如果小於對方則回傳 -1,大於對方則回傳 1,相等則回傳 0。 ‘小於’和‘大於’是由每個字串的 Unicode 碼點 決定的,這大致相當於字母表的順序。

如果兩個字串長度不同,當本字串比 to(參數名)字串更長時,回傳 1;如果更短,則回傳 -1。請注意,空字串的長度始終為 0。

如果想從字串比較中取得一個 bool(布林值)結果,請改用 == 運算符。另請參閱 nocasecmp_to()、filecasecmp_to() 和 naturalcasecmp_to()。


bool contains(what: String) const 🔗

如果該字串包含 what,則回傳 true。在 GDScript 中對應 in 運算符。

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

如果想要知道 what 在該字串中的位置,請使用 find()。另見 containsn()。


bool containsn(what: String) const 🔗

如果忽略大小寫,字串包含 what,則回傳 true。

如果你需要知道 what 在字串中的位置,請使用 findn()。另見 contains()。


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

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


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

返回子串 what 在 from 和 to 位置之間出現的次數,忽略大小寫。如果 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 超過字串的長度,返回的字串中擦除的字元數會少於請求的數量。如果 position 或 chars 為負數,則返回空字串。如果 chars 為 0 則返回原字串,不進行修改。


int filecasecmp_to(to: String) const 🔗

與 naturalcasecmp_to() 類似,但優先考慮以句點(.)和底線(_)開頭的字串,然後再考慮其他字元。在對資料夾或檔名進行排序時很有用。

要從字串比較中取得 bool 結果,請改用 == 運算符。另見 filenocasecmp_to()、naturalcasecmp_to() 和 casecmp_to()。


int filenocasecmp_to(to: String) const 🔗

與 naturalnocasecmp_to() 類似,但優先考慮以句點(.)和底線(_)開頭的字串,然後再考慮其他字元。在對資料夾或檔名進行排序時很有用。

要從字串比較中取得 bool 結果,請改用 == 運算符。另見 filecasecmp_to()、naturalnocasecmp_to() 和 nocasecmp_to()。


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

回傳 what 在該字串中第一次出現的索引,如果不存在則回傳 -1。搜尋的起點可以用 from 指定,持續到字串結尾。

print("Team".find("I")) # 輸出 -1

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

注意:如果你只是想要知道該字串中是否包含 what,請使用 contains()。在 GDScript 中,你還可以使用 in 運算符。

注意:from 的負值通過從最後一個有足夠空間找到 what 的索引開始倒數來轉換為起始索引。


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

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


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

對字串進行格式化,會將其中出現的所有 placeholder 都替換為 values 中的元素。

values 可以是 Dictionary、Array 或 Object。placeholder 中的底線都會事先替換為對應的鍵。陣列元素使用對應的索引作為鍵。

# 輸出“Waiting for Godot 是 Samuel Beckett 的戲劇,Godot 引擎由此得名。”
var use_array_values = "Waiting for {0} 是 {1} 的戲劇,{0} 引擎由此得名。"
print(use_array_values.format(["Godot", "Samuel Beckett"]))

# 輸出“第 42 號使用者是 Godot。”
print("第 {id} 號使用者是 {name}。".format({"id": 42, "name": "Godot"}))

當 values 為 Array 時還會執行一些額外的處理。如果 placeholder 不包含底線,則 values 陣列的元素將用於按順序替換出現的佔位符;如果 values 的元素也是包含兩個元素的陣列,則會被解釋為鍵值對。

# 輸出“第 42 號使用者是 Godot。”
print("第 {} 號使用者是 {}。".format([42, "Godot"], "{}"))
print("第 {id} 號使用者是 {name}。".format([["id", 42], ["name", "Godot"]]))

傳入 Object 時,會將 Object.get_property_list() 中的屬性名稱用作鍵。

# 輸出“可見 true,位置 (0, 0)”
var node = Node2D.new()
print("可見 {visible},位置 {position}".format(node))

另見 GDScript 格式化字串教學。

注意:會依序針對 values 的每個元素進行預留位置替換,並非同時完成。因此插入的元素中如果包含其他佔位符,就可能在下一次替換時發生改變。這是一把雙刃劍,常會導致預料之外的結果。除非必要,請確保 values 的元素中不包含佔位符。

print("{0} {1}".format(["{1}", "x"]))           # 輸出“x x”
print("{0} {1}".format(["x", "{0}"]))           # 輸出“x {0}”
print("{a} {b}".format({"a": "{b}", "b": "c"})) # 輸出“c c”
print("{a} {b}".format({"b": "c", "a": "{b}"})) # 輸出“{b} c”

注意:在 C# 中推薦改為使用「$」進行字串插值。


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 🔗

使用分隔符 delimiter 拆分該字串,回傳索引為 slice 的子串。如果字串中不存在 delimiter 則回傳原字串。如果 slice 不存在則回傳空字串。

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

print("i/am/example/hi".get_slice("/", 2)) # 輸出“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 🔗

回傳代表該字串內容的 32 位元雜湊值。

注意:由於雜湊碰撞的緣故,雜湊相同的字串不一定相同。而相對的是,雜湊不同的字串一定不同。


PackedByteArray hex_decode() const 🔗

將十六進位字串解碼為 PackedByteArray。

var text = "hello world"
var encoded = text.to_utf8_buffer().hex_encode() # 輸出 "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 🔗

Indents every line of the string with the given prefix. Empty lines are not indented. See also dedent() to remove indentation.

For example, the string can be indented with two tabulations using "\t\t", or four spaces using "    ".


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 🔗

如果這個字串中的所有字元都能在 text 中按照原始順序找到,則回傳 true。與 contains() 不同。

var text = "Wow, incredible!"

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

bool is_subsequence_ofn(text: String) const 🔗

如果這個字串中的所有字元都能在 text 中按照原始順序找到,忽略大小寫,則回傳 true。與 containsn() 不同。


bool is_valid_ascii_identifier() const 🔗

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

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

另見 is_valid_unicode_identifier()。


bool is_valid_filename() const 🔗

如果該字串為有效的檔名,則回傳 true。有效的檔名不能為空、頭尾不能是空白字元、不包含不允許的字元(: / \ ? * " | % < >)。


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。有效的十六進位數只能包含數位或字母 A 到 F(大小寫均可),還可以前綴正號(+)或負號(-)。

如果 with_prefix 為 true,則十六進位數需要有 "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 🔗

如果該字串是有效的 Unicode 標識符,則回傳 true。

有效的 Unicode 標識符必須使用 XID_Start 類的 Unicode 字元或 "_" 開頭,其他位置可以包含 XID_Continue 類的 Unicode 字元。

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

另見 is_valid_ascii_identifier()。

注意:該方法檢查標識符的規則與 GDScript 相同。使用更多進階規則見 TextServer.is_valid_identifier()。


String join(parts: PackedStringArray) const 🔗

回傳將 parts 中的元素連接組成的字串,元素間使用呼叫該方法的字串進行分隔。該方法和 split() 相反。

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

print(", ".join(fruits))  # 輸出 "Apple, Orange, Pear, Kiwi"
print("---".join(fruits)) # 輸出 "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 🔗

與另一個字串進行區分大小寫的自然順序比較。小於時回傳 -1、大於時回傳 1、等於時回傳 0。“小於”和“大於”比較的是字串中的 Unicode 碼位,大致與字母表順序一致。

使用自然順序進行排序時,會和常見預期一樣將連續的數字進行組合,而不是一個個數字進行比較。排序後的數列為 ["1", "2", "3", ...] 而不是 ["1", "10", "2", "3", ...]。

如果字串長度不同,這個字串比 to 字串長時回傳 1,短時回傳 -1。請注意空字串的長度始終為 0。

要從字串比較中獲得 bool 結果,請改用 == 運算符。另見 naturalnocasecmp_to()、filecasecmp_to() 和 nocasecmp_to()。


int naturalnocasecmp_to(to: String) const 🔗

與另一個字串進行不區分大小寫的自然順序比較。小於時回傳 -1、大於時回傳 1、等於時回傳 0。“小於”和“大於”比較的是字串中的 Unicode 碼位,大致與字母表順序一致。內部實現時,會將小寫字元轉換為大寫後進行比較。

使用自然順序進行排序時,會和常見預期一樣將連續的數字進行組合,而不是一個個數字進行比較。排序後的數列為 ["1", "2", "3", ...] 而不是 ["1", "10", "2", "3", ...]。

如果字串長度不同,這個字串比 to 字串長時回傳 1,短時回傳 -1。請注意空字串的長度始終為 0。

要從字串比較中獲得 bool 結果,請改用 == 運算符。另見 naturalcasecmp_to()、filenocasecmp_to() 和 casecmp_to()。


int nocasecmp_to(to: String) const 🔗

對另一個字串執行不區分大小寫的比較。如果(目前字串)小於目標字串,則回傳 -1;如果大於,則回傳 1;如果相等,則回傳 0。“小於”或“大於”是根據每個字串的 Unicode 碼點 來確定的,這大致上相當於字母表的排列順序。在內部處理時,所有小寫字元都會被轉換成大寫來進行比較。

如果兩個字串的長度不同,且目前字串比 to 參數指定的字串更長,則回傳 1;如果更短,則回傳 -1。請注意,空字串的長度始終為 0。

如果你想從字串比較中取得一個 bool(布林值)結果,請改用 == 運算符。也可以參考 casecmp_to()、filenocasecmp_to() 和 naturalnocasecmp_to() 這幾個方法。


String pad_decimals(digits: int) const 🔗

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


String pad_zeros(digits: int) const 🔗

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


String path_join(path: String) const 🔗

將 path 作為子路徑連接到該字串的末尾,必要時會新增 /。

範例:"this/is".path_join("path") == "this/is/path"。


String remove_char(what: int) const 🔗

移除字串中出現的所有碼位為 what 的 Unicode 字元。相較於呼叫 replace() 時鍵為單字串且替換為 "" 要快。


String remove_chars(chars: String) const 🔗

移除所有出現在 chars 中的字元。另見 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 🔗

將所有程式碼為 key 的 Unicode 字元都替換為程式碼為 with 的 Unicode 字元。這是 replace() 針對替換目標為單個字元的特化版本,速度更快。取得單個字元請使用 "X".unicode_at(0)(請注意,合成字元、Emoji 等字串是由多個 Unicode 碼位構成的,無法使用該方法,請使用 length() 判斷)。


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

將該字串中出現的所有 keys 中的字元都替換為碼位為 with 的 Unicode 字元。另見 replace_char()。


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

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


String reverse() const 🔗

回傳該字串的逆序的副本。該操作適用於 Unicode 程式碼點,而不是程式碼點序列,並且可能會破壞復合字母或表情符號等內容。


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

回傳這個字串中 what 最後一次出現時的索引,不存在時則為 -1。搜尋的起點可以用 from 指定,終點為該字串的開頭。這個方法與 find() 相對。

注意:from 的負值通過從最後一個有足夠空間找到 what 的索引開始倒數來轉換為起始索引。

注意:如果 from 的值大於能夠找到 what 的最後一個可能索引,則視為越界,並回傳 -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 🔗

使用分隔符 delimiter 將該字串從末尾開始進行拆分,回傳子字串陣列。回傳的陣列中,每部分的出現順序與它們在原字串中的出現順序一致。如果 delimiter 為空,則子串為單個字元。

如果 allow_empty 為 false,陣列中會排除相鄰分隔符之間的空字串。

如果 maxsplit 大於 0,則拆分次數不能超過 maxsplit。預設拆分整個字串,基本與 split() 一致。

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

print(some_array.size()) # 輸出 2
print(some_array[0])     # 輸出“One,Two,Three”
print(some_array[1])     # 輸出“Four”

String rstrip(chars: String) const 🔗

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

注意: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 🔗

回傳該字串與另一個字串的相似指數(索倫森-戴斯係數)。結果為 1.0 表示完全相似,0.0 表示完全不相似。

print("ABC123".similarity("ABC123")) # 輸出 1.0
print("ABC123".similarity("XYZ456")) # 輸出 0.0
print("ABC123".similarity("123ABC")) # 輸出 0.8
print("ABC123".similarity("abc123")) # 輸出 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 🔗

使用分隔符 delimiter 將該字串進行拆分,回傳子字串陣列。如果 delimiter 為空,則子串為單個字元。這個方法與 join() 相對。

如果 allow_empty 為 false,陣列中會排除相鄰分隔符之間的空字串。

如果 maxsplit 大於 0,則拆分次數不能超過 maxsplit。預設拆分整個字串。

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

print(some_array.size()) # 輸出 3
print(some_array[0])     # 輸出“One”
print(some_array[1])     # 輸出“Two”
print(some_array[2])     # 輸出“Three,Four”

注意:如果你只需要陣列中的某一個子串,請考慮使用更快的 get_slice()。如果你需要用更複雜的規則來拆分字串,請改用 RegEx 類。


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

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

如果 allow_empty 為 false,則會排除相鄰分隔符號之間為空或無法轉換為 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 🔗

Strips all non-printable characters from the beginning and the end of the string. These include spaces, tabulations (\t), and newlines (\n \r).

If left is false, ignores the string's beginning. Likewise, if right is false, ignores the string's end.


String strip_escapes() const 🔗

Strips all escape characters from the string. These include all non-printable control characters of the first page of the ASCII table (values from 0 to 31), such as tabulation (\t) and newline (\n, \r) characters, but not spaces.


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

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


PackedByteArray to_ascii_buffer() const 🔗

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


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 🔗

回傳將該字串轉換為烤串命名法 kebab-case 的結果。

注意:如果數字後跟著的是單個字母,則不會進行拆分,這是為了保證某些單詞的連貫(例如“2D”)。

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

String to_lower() const 🔗

回傳將該字串轉換為小寫 lowercase 的結果。


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

將字串轉換為使用系統多位元組程式碼頁編碼的 PackedByteArray。如果轉換失敗,則會回傳空陣列。

encoding 的有效值由系統決定。如果 encoding 為空字串,則會使用系統預設的編碼。

  • 對於 Windows,見程式碼頁標識符 .NET 名稱。

  • 對於 macOS 和 Linux/BSD,支援的編碼清單見 libiconv 庫文件及 iconv --list。


String to_pascal_case() const 🔗

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


String to_snake_case() const 🔗

回傳將該字串轉換為蛇形命名法 snake_case 的結果。

注意:如果數字後跟著的是單個字母,則不會進行拆分,這是為了保證某些單詞的連貫(例如“2D”)。

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

String to_upper() const 🔗

回傳將該字串轉換為大寫 UPPERCASE 的結果。


PackedByteArray to_utf8_buffer() const 🔗

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


PackedByteArray to_utf16_buffer() const 🔗

將該字串轉換為 UTF-16 編碼的 PackedByteArray。這是 PackedByteArray.get_string_from_utf16() 的逆運算。


PackedByteArray to_utf32_buffer() const 🔗

將該字串轉換為 UTF-32 編碼的 PackedByteArray。這是 PackedByteArray.get_string_from_utf32() 的逆運算。


PackedByteArray to_wchar_buffer() const 🔗

將該字串轉換為 寬字元(wchat_t,Windows 上為 UTF-16,其他平台上為 UTF-32)編碼的 PackedByteArray。這是 PackedByteArray.get_string_from_wchar() 的逆運算。


String trim_prefix(prefix: String) const 🔗

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


String trim_suffix(suffix: String) const 🔗

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


int unicode_at(at: int) const 🔗

回傳位於 at 的字元程式碼。

另見 String.chr()、@GDScript.char()、@GDScript.ord()。


String uri_decode() const 🔗

將該字串按照 URL 編碼格式進行解碼。該方法可以在收到 HTTP 請求時正確解碼 URL 中的參數。另見 uri_encode()。

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

注意:這個方法會將 + 解碼為空白。


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 🔗

按照 URL 編碼格式解析檔案路徑。與 uri_decode() 不同,該方法會保留 +。


String validate_filename() const 🔗

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


String validate_node_name() const 🔗

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


String xml_escape(escape_quotes: bool = false) const 🔗

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


String xml_unescape() const 🔗

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


運算子說明

bool operator !=(right: String) 🔗

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


bool operator !=(right: StringName) 🔗

如果該 StringName 與 right 不指向同一個名稱,則返回 true。StringName 間的比較比常規 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) 🔗

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


bool operator >(right: StringName) 🔗

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


bool operator >=(right: StringName) 🔗

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