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