Lua 字符串学习笔记
字符串的定义
在Lua中,字符串是指字符序列。Lua可以使用单引号(')或双引号(")来表示字符串。例如:
luaCopy Codestr1 = 'hello world'
str2 = "Lua is awesome"
字符串的连接
Lua中使用 ..
来连接两个字符串。
luaCopy Codestr3 = str1 .. str2
print(str3) -- 输出:hello worldLua is awesome
获取字符串长度
字符串的长度可以使用 #
操作符来获取。
luaCopy Codestr4 = "I love Lua"
print(#str4) -- 输出:10
字符串查找
string.find
可以使用string.find(s, pattern [, init [, plain]])
函数在字符串中查找指定字符串或模式。其中参数说明如下:
s
: 要查找的字符串。pattern
: 要查找的模式。init
: 查找的起始位置,默认值为1。plain
: 是否启用模式匹配,可选参数,默认为false。
例如:
luaCopy Codestr5 = "Welcome to Lua World"
pos = string.find(str5, "Lua")
print(pos) -- 输出:11
string.match
可以使用string.match(s, pattern [, init])
函数从字符串中提取匹配模式的子字符串。其中参数说明同string.find
。
例如:
luaCopy Codestr6 = "Today is 2023-06-03"
date = string.match(str6, "%d%d%d%d%-+%d%d%-+%d%d")
print(date) -- 输出:2023-06-03
字符串替换
可以使用string.gsub(s, pattern, repl [, n])
函数将指定字符串或模式替换为指定子字符串。其中参数说明如下:
s
: 要进行替换的字符串。pattern
: 要替换的模式。repl
: 要替换成的子字符串。n
: 最多替换n次。
例如:
luaCopy Codestr7 = "I love Lua"
newStr = string.gsub(str7, "Lua", "programming language")
print(newStr) -- 输出:I love programming language
以上是Lua字符串的基本操作,还有很多其他功能可供学习和探索。