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.
Checking the stable version of the documentation...
String
字串內建型別。
說明
這是內建的字串 Variant 型別(GDScript 使用的就是這個型別)。字串中可以包含任意數量的 Unicode 字元,暴露的方法可用於字串的操作和生成。字串有參照計數,使用寫時複製技術(每次對字串的修改都會回傳新的 String),所以傳遞字串的資源損耗很小。
部分字串方法有對應的變體。後綴 n 的變體(countn()、findn()、replacen() 等)大小寫不敏感(不區分大寫字元和小寫字元)。前綴 r 的方法變體(rfind()、rsplit() 等)是逆序的,會從字串末尾開始,而不是從開頭開始。
任意 Variant 和字串之間的相互轉換見 @GlobalScope.str()、@GlobalScope.str_to_var()、@GlobalScope.var_to_str()。
注意:在布林語境下,空字串("")的求值結果為 false。否則字串的求值結果始終為 true。
備註
使用 C# 操作此 API 時有顯著差異,詳見 C# API 與 GDScript 的不同。
教學
建構子
String() |
|
String(from: StringName) |
方法
運算子
operator !=(right: String) |
|
operator !=(right: StringName) |
|
operator %(right: Variant) |
|
operator +(right: String) |
|
operator +(right: StringName) |
|
operator <(right: String) |
|
operator <=(right: String) |
|
operator ==(right: String) |
|
operator ==(right: StringName) |
|
operator >(right: String) |
|
operator >=(right: String) |
|
operator [](index: int) |
建構子說明
建構空的 String("")。
建構給定 String 的副本。
從給定的 NodePath 建構新的 String。
String String(from: StringName)
從給定的 StringName 建構新 String。
方法說明
bool begins_with(text: String) const 🔗
如果該字串以給定的 text 開始,則返回 true。另見 ends_with()。
PackedStringArray bigrams() const 🔗
返回包含該字串的雙字母組(連續字母的組合)的陣列。
print("Get up!".bigrams()) # 輸出 ["Ge", "et", "t ", " u", "up", "p!"]
將表示二進位數字的字串轉換為 int。該字串可以前綴 "0b",負數可以前綴 -。
print("101".bin_to_int()) # 輸出 5
print("0b101".bin_to_int()) # 輸出 5
print("-0b10".bin_to_int()) # 輸出 -2
GD.Print("101".BinToInt()); // 輸出 5
GD.Print("0b101".BinToInt()); // 輸出 5
GD.Print("-0b10".BinToInt()); // 輸出 -2
返回該字串的副本,按照 C 語言標準對特殊字元進行轉義。
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.
回傳一個外觀經過修改的字串副本。它會將底線(_)和連字元(-)替換為空白,並在單詞中間的大寫字母前新增空白,然後將所有字母轉換為小寫,最後再將首字母以及每個空白後的字母轉換為大寫。
"move_local_x".capitalize() # Returns "Move Local X"
"sceneFile_path".capitalize() # Returns "Scene File Path"
"2D, FPS, PNG".capitalize() # Returns "2d, Fps, Png"
"example-name".capitalize() # Returns "Example Name"
"move_local_x".Capitalize(); // Returns "Move Local X"
"sceneFile_path".Capitalize(); // Returns "Scene File Path"
"2D, FPS, PNG".Capitalize(); // Returns "2d, Fps, Png"
"example-name".Capitalize(); // Returns "Example Name"
int casecmp_to(to: String) const 🔗
與另一個字串進行區分大小寫的比較。如果小於對方則回傳 -1,大於對方則回傳 1,相等則回傳 0。“小於”和“大於”是由每個字串的 Unicode 碼點 決定的,這大致對應字母表的順序。
如果字元比較進行到了其中一個字串的末尾,而另一個字串還包含更多字元,那麼長度將成為決定因素:如果本字串比 to 字串更長,則回傳 1,如果更短則回傳 -1。請注意,空字串的長度始終為 0。
如果想從字串比較中取得一個 bool(布林值)結果,請改用 == 運算符。另請參閱 nocasecmp_to()、filecasecmp_to() 和 naturalcasecmp_to()。
String chr(code: int) static 🔗
根據整數 code 回傳單一 Unicode 字元。可以參考 unicodelookup.com 和 unicode.org。
print(String.chr(65)) # 輸出 "A"
print(String.chr(129302)) # 輸出 "🤖"(機器人臉 Emoji)
另見 unicode_at()、@GDScript.char()、@GDScript.ord()。
bool contains(what: String) const 🔗
如果該字串包含 what,則回傳 true。在 GDScript 中對應 in 運算符。
print("Node".contains("de")) # 輸出 true
print("team".contains("I")) # 輸出 false
print("I" in "team") # 輸出 false
GD.Print("Node".Contains("de")); // 輸出 True
GD.Print("team".Contains("I")); // 輸出 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,會在剩餘字串中繼續搜尋。
返回刪除了縮進(前導定位字元和空格)的字串副本。新增縮進請參閱 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
GD.Print("Team".Find("I")); // 輸出 -1
GD.Print("Potato".Find("t")); // 輸出 2
GD.Print("Potato".Find("t", 3)); // 輸出 4
GD.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# 中推薦改為使用「$」進行字串插值。
如果該字串是有效的檔路徑,則返回基礎目錄名稱。
var dir_path = "/path/to/file.txt".get_base_dir() # dir_path 為 "/path/to"
如果該字串是有效的檔路徑,則返回完整檔路徑,不包括副檔名。
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 為 ""
如果該字串是有效的檔路徑,則返回呼函式案名,包括副檔名。
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())。
使用 get_slice() 提取特定切片。
print("i/am/example/string".get_slice_count("/")) # 輸出 “4”。
print("i am example string".get_slice_count("/")) # 輸出 “1”。
String get_slicec(delimiter: int, slice: int) const 🔗
使用 Unicode 字元碼分隔符 delimiter 拆分該字串,回傳索引為 slice 的子串。如果 slice 不存在則回傳空字串。
只需要一兩個子串時這個方法比 split() 快。
這是 get_slice() 的 Unicode 版本。
回傳代表該字串內容的 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())
var text = "hello world";
var encoded = text.ToUtf8Buffer().HexEncode(); // 輸出 "68656c6c6f20776f726c64"
GD.Print(encoded.HexDecode().GetStringFromUtf8());
將表示十六進位數的字串轉換為 int。該字串可以前綴 "0x",負數可以前綴 -。
print("0xff".hex_to_int()) # 輸出 255
print("ab".hex_to_int()) # 輸出 171
GD.Print("0xff".HexToInt()); // 輸出 255
GD.Print("ab".HexToInt()); // 輸出 171
String humanize_size(size: int) static 🔗
將表示位元組數的 size 轉換為人類可讀的形式。
結果使用 IEC 詞頭,結尾可能是 "B"、"KiB"、"MiB"、"GiB"、"TiB"、"PiB" 或 "EiB"。
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:\"、"/" 等開頭的路徑。
如果該字串的長度為 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。有效的檔名不能為空、頭尾不能是空白字元、不包含不允許的字元(: / \ ? * " | % < >)。
如果該字串代表有效的浮點數,則返回 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
如果該字串代表有效的整數,則返回 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[] fruits = ["Apple", "Orange", "Pear", "Kiwi"];
// 這個方法在 C# 中是靜態的。
GD.Print(string.Join(", ", fruits)); // 輸出 "Apple, Orange, Pear, Kiwi"
GD.Print(string.Join("---", fruits)); // 輸出 "Apple---Orange---Pear---Kiwi"
返回該字串的副本,使用 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"
返回該字串中的字元數。空字串("")始終返回 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。
返回該字串的 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 code points,大致與字母表順序一致。內部實現時,會將小寫字元轉換為大寫後進行比較。
使用自然順序進行排序時,會和常見預期一樣將連續的數字進行組合,而不是一個個數字進行比較。排序後的數列為 ["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 num(number: float, decimals: int = -1) static 🔗
將 float 轉換為十進位小數的字串表示,小數點位數由 decimals 指定。
如果 decimals 為預設的 -1,該字串表示可能最多只有 14 位元有效數字,小數點前的數字優先於小數點後的數字。
該字串中不包含後綴的零。最後一位數字會四捨五入,而不是截斷。
String.num(3.141593) # 回傳 "3.141593"
String.num(3.141593, 3) # 回傳 "3.142"
String.num(3.14159300) # 回傳 "3.141593"
# 此處的最後一位數字會進位,
# 數字位數會減少,因為後綴的零會被移除:
String.num(42.129999, 5) # 回傳 "42.13"
# 如果沒有指定 `decimals`,最大有效位數為 14:
String.num(-0.0000012345432123454321) # 回傳 "-0.00000123454321"
String.num(-10000.0000012345432123454321) # 回傳 "-10000.0000012345"
String num_int64(number: int, base: int = 10, capitalize_hex: bool = false) static 🔗
將給定的數位 number 轉換為字串表示,進位元制由 base 給定。
預設情況下 base 為十進位(10)。程式設計中常見的進位制還有二進位(2)、八進位(8)、十六進位(16)。
如果 capitalize_hex 為 true,比 9 大的數位會大寫。
String num_scientific(number: float) static 🔗
將數字 number 轉換為字串表示,使用科學記數法。
var n = -5.2e8
print(n) # 輸出 -520000000
print(String.num_scientific(n)) # 輸出 -5.2e+08
// 這個方法沒有在 C# 中實作。
// 請在 `string.ToString()` 中使用 "e" 來實作類似的結果。
var n = -5.2e8f;
GD.Print(n); // 輸出 -520000000
GD.Print(n.ToString("e1")); // 輸出 -5.2e+008
注意:這個方法沒有在 C# 中實作。要實作類似的效果,見 C# 的標準數字格式字串。
String num_uint64(number: int, base: int = 10, capitalize_hex: bool = false) static 🔗
將給定的無符號 int 轉換為字串表示,進位元制由 base 給定。
預設情況下 base 為十進位(10)。程式設計中常見的進位制還有二進位(2)、八進位(8)、十六進位(16)。
如果 capitalize_hex 為 true,比 9 大的數位會大寫。
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,大小寫不敏感。
回傳該字串的逆序的副本。該操作適用於 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”
// C# 中沒有 String.RSplit() 方法。
String rstrip(chars: String) const 🔗
從該字串的結尾移除 chars 中定義的字元。另見 lstrip()。
注意:chars 不是後綴。如果要移除後綴而不是一組字元,請使用 trim_suffix()。
PackedByteArray sha1_buffer() const 🔗
返回該字串的 SHA-1 雜湊,類型為 PackedByteArray。
返回該字串的 SHA-1 雜湊,類型為 String。
PackedByteArray sha256_buffer() const 🔗
返回該字串的 SHA-256 雜湊,型別為 PackedByteArray。
返回該字串的 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”
// C# 的 `Split()` 不支援 `maxsplit` 參數。
var someArray = "One,Two,Three".Split(",");
GD.Print(someArray[0]); // 輸出“One”
GD.Print(someArray[1]); // 輸出“Two”
GD.Print(someArray[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。該方法會在首個非數位字元處停止,除非是首次遇到 .(小數點)以及表示指數的 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。該方法會刪除所有非數位字元,並在遇到 . 後停止。另見 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"
"Node2D".ToKebabCase(); // 回傳 "node-2d"
"2nd place".ToKebabCase(); // 回傳 "2-nd-place"
"Texture3DAssetFolder".ToKebabCase(); // 回傳 "texture-3d-asset-folder"
回傳將該字串轉換為小寫 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"
"Node2D".ToSnakeCase(); // 回傳 "node_2d"
"2nd place".ToSnakeCase(); // 回傳 "2_nd_place"
"Texture3DAssetFolder".ToSnakeCase(); // 回傳 "texture_3d_asset_folder"
回傳將該字串轉換為大寫 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 的字元程式碼。
另見 chr()、@GDScript.char()、@GDScript.ord()。
將該字串按照 URL 編碼格式進行解碼。該方法可以在收到 HTTP 請求時正確解碼 URL 中的參數。另見 uri_encode()。
var url = "$DOCS_URL/?highlight=Godot%20Engine%3%docs"
print(url.uri_decode()) # 輸出 "$DOCS_URL/?highlight=Godot Engine:docs"
var url = "$DOCS_URL/?highlight=Godot%20Engine%3%docs"
GD.Print(url.URIDecode()) // 輸出 "$DOCS_URL/?highlight=Godot Engine:docs"
注意:這個方法會將 + 解碼為空白。
將該字串按照對 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"
var prefix = "$DOCS_URL/?highlight=";
var url = prefix + "Godot Engine:docs".URIEncode();
GD.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,則單引號(')和雙引號(")字元也會被轉義。
返回該字串的副本,轉義字元均按照 XML 標準使用本義代替。
運算子說明
bool operator !=(right: String) 🔗
如果兩個字串不以相同的字元序列開頭,則返回 true。
bool operator !=(right: StringName) 🔗
如果該 String 與給定的 StringName 不等價,則返回 true。
String operator %(right: Variant) 🔗
格式化該 String,使用若干參數替換預留位置。要傳遞多個參數,right 需要為 Array。
print("我捉到了 %d 條魚!" % 2) # 輸出 "我捉到了 2 條魚!"
var my_message = "正在前往 %s,速度為 %2.2f km/h。"
var location = "深谷"
var speed = 40.3485
print(my_message % [location, speed]) # 輸出 "正在前往深谷,速度為 40.35 km/h。"
更多資訊見《GDScript 格式字串》教學。
注意:C# 中沒有等價的運算子。見如何使用“$”插入字串。
String operator +(right: String) 🔗
將 right 追加到該 String 的末尾,也稱作字元串連接。
String operator +(right: StringName) 🔗
將 right 追加到該 String 的末尾,返回 String。也稱作字元串連接。
bool operator <(right: String) 🔗
如果左側的 String 比 right 靠前,則返回 true。使用的是 Unicode 順序,大致與字母表順序一致。可用於排序。
bool operator <=(right: String) 🔗
如果左側的 String 比 right 靠前,或兩者相等,則返回 true。使用的是 Unicode 順序,大致與字母表順序一致。
bool operator ==(right: String) 🔗
如果兩個字串以相同的字元序列開頭,則返回 true。
bool operator ==(right: StringName) 🔗
如果該 String 與給定的 StringName 等價,則返回 true。
bool operator >(right: String) 🔗
如果左側的 String 比 right 靠後,則返回 true。使用的是 Unicode 順序,大致與字母表順序一致。可用於排序。
bool operator >=(right: String) 🔗
如果左側的 String 比 right 靠後,或兩者相等,則返回 true。使用的是 Unicode 順序,大致與字母表順序一致。
String operator [](index: int) 🔗
返回只包含索引為 index 的字元的新 String。索引從 0 開始。如果 index 大於等於 0,則字元是從該字串的開頭開始取得的。如果 index 為負,則從末尾開始取得。越界存取字串會導致運作時錯誤,從編輯器中運作時會將專案暫停。