您的位置:首页 > 编程语言 > Lua

Lua 标准库 - 字符串处理(string manipulation)

2007-10-16 17:42 387 查看
字符串库为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为函数时:每次查找到字符都将

(待续 CashChin)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: