跳轉到內容

Lua 程式設計/stringlib

來自 Wikibooks,開放世界的開放書籍

string.byte

[編輯 | 編輯原始碼]

string.char

[編輯 | 編輯原始碼]

string.dump

[編輯 | 編輯原始碼]

string.find

[編輯 | 編輯原始碼]

string.format

[編輯 | 編輯原始碼]

string.gmatch

[編輯 | 編輯原始碼]

string.gsub

[編輯 | 編輯原始碼]

string.len

[編輯 | 編輯原始碼]
string.len(STRING)

string.len 函式 返回 字串 引數的長度。

print (string.len("Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"))  -- Returns 58
嵌入空字元
[編輯 | 編輯原始碼]

嵌入 字元不會終止 字串 ,而且也會被此 函式 計數。

print (string.len("ab\000cd\000"))  -- Returns 6
長度運算子也可以用來確定字串的長度
[編輯 | 編輯原始碼]

lua 程式語言提供了一個 長度運算子 ,它也可以用來確定 字串 的長度

print (#"Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch")  -- Returns 58

string.lower

[編輯 | 編輯原始碼]

string.match

[編輯 | 編輯原始碼]

string.rep

[編輯 | 編輯原始碼]

string.reverse

[編輯 | 編輯原始碼]
string.reverse(STRING)

string.reverse 函式 可用於反轉字串,並返回其字元順序反轉的字串

print (string.reverse("anut fo raj a rof tun A"))  -- A nut for a jar of tuna

string.sub

[編輯 | 編輯原始碼]
string.sub(STRING, STARTPOS [, ENDPOS])

string.sub 函式 返回 字串 引數從起始位置到可選的結束位置的子字串。

print (string.sub("cheese salad sandwich",8))  -- position 8 onwards gives us "salad sandwich"
print (string.sub("cheese salad sandwich",1,12)  -- positions 1 to 12 gives us "cheese salad"
起始位置不能省略,但結束位置可以省略。
[編輯 | 編輯原始碼]

請注意,起始位置不是可選的,因此對於從第一個位置開始的 子字串,必須提供一個引數 1。

-- This does not work
print (string.sub("cheese salad sandwich",,12)  -- we cannot omit the start position
-- To fix this, we must provide a substring position
print (string.sub("cheese salad sandwich",1,12)  -- we want a substring from position 1

結束位置可以省略或為負數。

[編輯 | 編輯原始碼]

如果沒有結束位置, 子字串 將一直延續到 字串 的末尾。

print (string.sub("cheese salad sandwich",8))  -- position 8 onwards gives us "salad sandwich"

字串位置可以為負數。

[編輯 | 編輯原始碼]

結束位置可以為負數。負值表示從末尾算起的字元數量,其中 -1 表示最後一個字元,-2 表示倒數第二個字元,依此類推。

print (string.sub("cheese salad sandwich",-8))  -- start 8 characters from the end gives "sandwich"
print (string.sub("cheese salad sandwich",1,-9))  -- drop " sandwich" to give "cheese salad"

string.upper

[編輯 | 編輯原始碼]
華夏公益教科書