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)

反转字符串