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

开发 前端
字符串库为Lua提供简易的字符串处理操作,所有的字串操作都是以1为基数的(C以0),也可使用负向索引,最后一个索引为-1 ; 所有的函数都存放在string表,并且已建立元表。

字符串库为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为函数时:每次查找到字符都将

原文链接:

责任编辑:陈四芳 来源: 来自ITPUB论坛
相关推荐

2013-12-12 16:59:15

Lua表处理

2011-08-23 14:26:07

Lua字符串

2013-12-12 17:27:51

Lua协同

2013-12-12 17:03:57

Lua脚本语言

2010-11-26 09:51:54

MySQL字符串

2020-05-12 08:53:15

JavaScript字符串处理库

2021-08-26 11:41:50

字符串String.jsVoca

2023-10-27 07:03:22

字符串String类型

2010-06-04 14:59:06

MySQL数据库

2010-07-14 16:35:52

Perl字符串处理函数

2010-08-04 11:23:15

Flex字符串

2013-12-03 17:28:56

Lua脚本语言

2010-10-09 11:54:46

MySQL字符串

2010-07-19 15:07:46

Perl字符串处理函数

2013-12-12 17:21:46

Lua出入输出

2021-05-27 08:59:09

String字符串操作

2021-11-07 07:51:01

JavaString字符串

2016-12-30 13:32:24

字符串算法代码

2009-11-26 16:26:32

PHP字符串mbstr

2024-03-05 18:29:54

JavaString字符串
点赞
收藏

51CTO技术栈公众号