Lua標準庫 - 字符串處理(string manipulation)
字符串庫為Lua提供簡易的字符串處理操作,所有的字串操作都是以1為基數的(C以0),也可使用負向索引,最后一個索引為-1 ; 所有的函數都存放在string表,并且已建立元表(__index=string表)
所以string.byte(s,i) <=> s:byte(i)
1、string.byte(s [, i [, j]])
功能:返回從i到j的字符所對應的數值(字符 到 ASCII值),i默認為1,j默認為i的值
如:s="123456" s:(1,2) => 49 50
--------------------------------------------------------------------------------
2、string.char (···)
功能:返回ASCII值參數對應的字符串
如:string.char(49,50) => 12
--------------------------------------------------------------------------------
3、string.dump(function)
功能:返回指定函數的二進制代碼(函數必須是一個Lua函數,并且沒有上值)
--------------------------------------------------------------------------------
4、string.find(s, pattern [, init [, plain]])
功能:查找s中首次出現pattern的位置,如果找到則返回首次出現的起始和結束索引否則返回nil
init:為搜索位置的起始索引,默認為1(也可以用負索引法表示)
plain:true 將關閉樣式簡單匹配模式,變為無格式匹配
--------------------------------------------------------------------------------
5、string.format (formatstring, ···)
功能:格式化字符串formatstring參數與C差不多
其中:*, l, L, n, p, h不被支持
c, d, E, e, f, g, G, i, o, u, X, x:接受數字參數
q, s:接受字符串參數
%q:為自動將對應參數字串中的特殊字符加上\
如:string.format('%q', 'a string with "quotes" and \n new line')等于
"a string with \"quotes\" and \
new line"
注:此函數不能接受字符串中間帶\0的字符
--------------------------------------------------------------------------------
6、string.gmatch(s, pattern)
功能:返回一個迭代函數,每次調用此函數,將返回下一個查找到的樣式串對應的字符
如: s = "hello world from Lua"
for w in string.gmatch(s, "%a+") do
print(w)
end
為 hello
word
from
Lua
字串到表的賦值
t = {}
s = "from=world, to=Lua"
for k, v in string.gmatch(s, "(%w+)=(%w+)") do
t[k] = v
end
--------------------------------------------------------------------------------
7、string.gsub (s, pattern, repl [, n])
功能:返回一個經repl替換pattern的字符串及替換的次數
s:待替換的字串
pattern:查找的字串
repl:要替換的內容(可以為字串,表,函數)
當repl為字符串時:進行對應字串的替換,%0~%9 %0為全匹配 %% 為%
當repl為表時:
當repl為函數時:每次查找到字符都將
原文鏈接: