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

字符串库为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)

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值