Lua开发--字符串操作

字符串表示
lua的字符串类型用单引号/双引号/2个方括号表示

t1="hello"
t2='hell0'
t3=[[hello]]

字符串操作
1)string.upper(str)
将字符串全部转为大写字母

x='asas'
print(string.upper(x))
--ASAS

2)string.lower(str)
将字符串全部转为小写字母

x='ASAS'
print(string.lower(x))
--asas

3)string.reverse(str)

x='hello'
print(string.reverse(x))
--olleh

4)string.gsub(mainstr,findstr,replacestr,num)
在字符串中替换,得到替换后的字符和替换次数

mainstr:要操作的字符串
findstr:要被替换的字符
replacestr:替换的字符
num:替换的次数,忽略则全部替换

x='hello'
print(string.gsub(x,'l','H'))
print(string.gsub(x,'ll','HH'))
--heHHo   2
--heHHo   1

5)string.find(str,s)
返回匹配串s在str中"开始和结束的下标"(如果不存在匹配串返回nil)

print(string.find("hello world!","ll"))
print(string.find("hello world!","ls"))
--3       4
--nil

6)string.format(str)
格式化字符串

y=string.format("I have %d apples",3)
print(y)
--I have 3 apples

7)string.len(str)
获取字符串长度

x='hello'
print(string.len(x))
--5

8)string.char(number)
将整型转换为字符型
9)string.byte(chr,i)
将字符串转换为整型,i表示指定第i个字符,默认第一个

print(string.char(65,66,67,68))
print(string.byte('hello'))

--ABCD
--104

10)string.rep(str,n)

print(string.rep("abcd",2))
--abcdabcd

11)连接字符串

print("a"..":".."b")
--a:b

12)string.match(str, pattern, init)
1.只寻找源字串str中的第一个配对. 参数init可选, 指定搜寻过程的起点, 默认为1
2.在成功配对时, 函数将返回配对表达式中的所有捕获结果; 如果没有设置捕获标记, 则返回整个配对字符串. 当没有成功的配对时, 返回nil

print(string.match("I have 2 questions for you.", "%d+ %a+"))
print(string.format("%d, %q", string.match("I have 2 questions for you.", "(%d+) (%a+)")))

--2 questions
--2, "questions"

13)string.gmatch(str, pattern)
返回一个迭代器函数,每调用一次这个函数,返回一个在字符串 str 找到的下一个符合 pattern 描述的子串。如果参数 pattern 描述的字符串没有找到,迭代函数返回nil

for word in string.gmatch("Hello world", "%a+") do print(word) end
--Hello
--world

14)string.sub(str,i,j)
字符串截取

s:要截取的字符串
i:截取的开始位置
j:截取的结束位置,默认为-1

s="hello world"
print(string.sub(s,5))
--o world
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值