Lua中的string库(字符串函数库)提供了一系列常见的字符串操作函数,本篇攻略将对这些函数进行详细的讲解和总结。
一、字符串的基础操作
1. 字符串长度
字符串长度可以通过#
运算符来获取,如下所示:
local str = "hello world"
print(#str) --> 11
2. 字符串连接
Lua中,使用..
运算符来连接两个或多个字符串,如下所示:
local str1 = "hello"
local str2 = "world"
local str3 = "!"
local str4 = str1 .. " " .. str2 .. str3
print(str4) --> "hello world!"
3. 字符串重复
字符串重复可以使用string.rep(str, n)
函数来实现,其中str
为要重复的字符串,n
为重复次数,如下所示:
local str = "hello"
print(string.rep(str, 3)) --> "hellohellohello"
4. 字符串截取
字符串截取可以使用string.sub(str, start, end)
函数来实现,其中str
为原始字符串,start
和end
为要截取的子字符串的起始下标和终止下标。如果end
省略,则默认截取到字符串末尾,如下所示:
local str = "hello world!"
print(string.sub(str, 1, 5)) --> "hello"
print(string.sub(str, 7)) --> "world!"
5. 字符串查找
字符串查找可以使用string.find(str, pattern[, init[, plain]])
函数来实现,其中str
为要查找的字符串,pattern
为要匹配的模式,init
为起始查找位置,默认为1,plain
为是否不开启模式匹配,默认为false。如果找到匹配的子串,则返回子串的起始下标和终止下标,否则返回nil,如下所示:
local str = "hello world!"
local start, finish = string.find(str, "world")
print(start, finish) --> 7 11
6. 字符串替换
字符串替换可以使用string.gsub(str, pattern, repl[, n])
函数来实现,其中str
为要替换的字符串,pattern
为要匹配的模式,repl
为替换后的字符串,n
为最大替换次数,默认为全部替换。该函数返回值为替换后的新字符串以及实际替换的次数,如下所示:
local str = "hello world!"
local newStr, count = string.gsub(str, "world", "Lua")
print(newStr) --> "hello Lua!"
print(count) --> 1
7. 字符串分割
字符串分割可以使用string.gmatch(str, pattern)
和string.match(str, pattern)
函数来实现,其中str
为要分割的字符串,pattern
为分割符。string.gmatch
函数返回值为迭代器,每次迭代返回匹配到的字符串,直到分割完毕。string.match
函数返回值为第一个匹配到的子串,如下所示:
local str = "hello, world, Lua"
for word in string.gmatch(str, "%a+") do
print(word)
end
--> "hello"
--> "world"
--> "Lua"
二、字符串的格式化操作
字符串格式化可以使用string.format(fmt, ...)
函数来实现,其中fmt
为格式化字符串,...
为可变参数,即需要格式化的变量。格式化字符串中,可使用%
转义符号来进行格式化,如下所示:
local str = string.format("value is %d, and string is '%s'", 10, "hello")
print(str) --> "value is 10, and string is 'hello'"
常见的格式化转义符如下:
转义符 | 描述 |
---|---|
%d |
十进制整数 |
%x |
十六进制整数 |
%f |
浮点数 |
%s |
字符串 |
%% |
百分号符号 |
%q |
将字符串格式化为可以被 Lua 解析器读入的格式(带有引号的字符串) |
三、其它字符串操作
除了上述的常见字符串操作之外,还有一些其它的字符串操作函数,如下所示:
1. 字符串转换为小写或大写
字符串转换为小写或大写可以使用string.lower(str)
和string.upper(str)
函数来实现,如下所示:
local str = "Hello World!"
print(string.lower(str)) --> "hello world!"
print(string.upper(str)) --> "HELLO WORLD!"
2. 字符串修剪
字符串修剪可以使用string.gsub(str, "^%s*(.-)%s*$", "%1")
函数来实现,其中str
为原始字符串。该函数的实现原理为使用正则表达式匹配字符串开头和结尾的空白字符,并将其去除,如下所示:
local str = " hello world! "
print(string.gsub(str, "^%s*(.-)%s*$", "%1")) --> "hello world!"
以上就是本篇攻略对Lua中的string库进行的详细讲解和总结。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Lua中的string库(字符串函数库)总结 - Python技术站