Lua 程式設計/stringlib
外觀
< Lua 程式設計
string.len(STRING)
print (string.len("Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch")) -- Returns 58
print (string.len("ab\000cd\000")) -- Returns 6
lua 程式語言提供了一個 長度運算子 ,它也可以用來確定 字串 的長度
print (#"Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch") -- Returns 58
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, 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"