lua 字符串處理

string.byte(s [, i [, j]])

string.byte是用來把字符轉換成ascii數字,s爲目標字符串,i爲索引開始位置(從1開始),j爲索引結束位置函數

string.char(...)

例子

--默認爲第1個返回a的ascii值
local r = string.byte('abcdefg')    --97

--從索引2(b)到索引4(d)也就是分別返回bcd的ascii值
local r1,r2,r3 = string.byte('abcdefg',2,4)    --98,99,100

--返回98所對應的字符
local r = string.char(98)    --a

--返回98,,99,100對應的字符並連在一塊兒返回
local r = string.char(98,99,100)    --abc

string.sub (s, i [, j])

截取字符串(字符串分割,字符串截取),i爲起始索引,可選參數j爲結束索引(包含),均可覺得負數,第一個字符索引爲1,最後一個字符爲-1spa

例子

local res,s
s = 'www.freecls.com'
res = string.sub(s,5)     --freecls.com
res = string.sub(s,5,-1)  --freecls.com

--截取後3位
res = string.sub(s,-3)    --com

--截取前3位
res = string.sub(s,1,3)   --www

string.dump(function)

函數序列化成字符串來保存那麼下次要使用的時候直接用loadstring或loadfile就能夠還原函數code

例子

function say()
    print('hello')
end

local f_str = string.dump(say)
print(f_str)    --uaQ

--復原函數
local func = loadstring(f_str)
func()

--若是咱們把f_str保存到了文件tmp.txt則能夠用loadfile('tmp.txt')來還原函數

string.find (s, pattern [, init [, plain]])

字符串查找函數找不到返回nil,找到了返回開始位置和結束位置,init爲從哪裏開始默認爲1,plain默認爲false表示利用模式匹配,若是設爲true則表示純文本匹配(也就是關閉正則匹配)orm

例子

local str = 'i love programming,11,22,%d+aa'
local s = string.find(str,'222')    --nil
s = string.find(str,'pro')  --8
s = string.find(str,",%d+")    --19(匹配到了,11)
s = string.find(str,",%d+",1,true)    --25(因爲關閉了模式匹配,因此匹配到了,%d+)

string.match (s, pattern [, init])

它跟string.find差很少,只不過能把捕獲匹配到的結果並返回blog

例子

local s,res,res1,res2
s = 'http://www.freecls.com'

--因爲沒有捕獲,返回所有匹配
--結果:http://www.freecls.com
res = string.match(s,'http://%a+\.%a+\.com')

--若是有捕獲,則分別返回捕獲結果
--結果:www    freecls
res1,res2 = string.match(s,'http://(%a+)\.(%a+)\.com')

string.gsub (s, pattern, repl [, n])

用來作字符串替換,可選參數n表明替換多少次默認所有替換,返回替換後的字符串索引

例子

local s,res,res1,res2
s = 'http://www.freecls.com'

--結果:http://test.freecls.com
res = string.gsub(s,'www','test')

--捕獲替換
--結果:test.freecls.abc
res = string.gsub(s,'^http://%w+\.(%w+)\.com$','test.%1.abc')

--w替換成t,可是隻替換2次
--結果:http://ttw.freecls.com
res = string.gsub(s,'w','t',2)

string.gmatch (s, pattern)

迭代匹配ci

例子

local s = 'www.freecls.com'
words = {}
for w in string.gmatch(s, "%a+") do
    words[#words + 1] = w
end
--words最終結果爲
--{'www','freecls','com'}

string.format (formatstring, ···)

字符串格式化類型c語言的sprintf不說廢話以例子來說解字符串

local s = string.format('%d%s',123,'freecls')   --123freecls

s = string.format('%0.2f',1.234343)     --1.23(保留2位)

--轉成16進制,%X爲大寫的16進制
local s = string.format('%X',140)       --8C
local s = string.format('%x',140)       --8c
local s = string.format('%04x',140)     --008c

string.len(s)

返回字符串長度string


string.rep(s,n)

字符串重複n次並拼接返回it


string.lower(s)

轉小寫


string.upper(s)

轉大寫


string.reverse(s)

反轉字符串

相關文章
相關標籤/搜索