Skip to content

字符串

字符串是 Lua 中用于表示文本的数据类型。本章节将介绍 Lua 中字符串的基本操作和常用方法。

字符串定义

字符串可以用单引号、双引号或 [[]] 表示:

lua
local str1 = 'Hello'
local str2 = "World"
local str3 = [[
  这是
  多行字符串
]]

print(str1)  -- 输出 Hello
print(str2)  -- 输出 World
print(str3)  -- 输出多行字符串

字符串连接

使用 .. 运算符连接字符串:

lua
local str1 = "Hello"
local str2 = "World"
local str3 = str1 .. " " .. str2
print(str3)  -- 输出 Hello World

字符串长度

使用 # 运算符获取字符串长度:

lua
local str = "Hello"
print(#str)  -- 输出 5

字符串索引

字符串中的每个字符都有一个索引,从 1 开始:

lua
local str = "Hello"
print(str:sub(1, 1))  -- 输出 H
print(str:sub(2, 2))  -- 输出 e
print(str:sub(3, 3))  -- 输出 l
print(str:sub(4, 4))  -- 输出 l
print(str:sub(5, 5))  -- 输出 o

字符串方法

Lua 提供了丰富的字符串方法,以下是一些常用的方法:

sub(start, end)

返回字符串的子串,从 start 位置到 end 位置:

lua
local str = "Hello World"
print(str:sub(1, 5))  -- 输出 Hello
print(str:sub(7, 11))  -- 输出 World

find(pattern, start, plain)

查找字符串中的子串,返回起始位置和结束位置:

lua
local str = "Hello World"
local start, end = str:find("World")
print(start, end)  -- 输出 7  11

gsub(pattern, replacement, count)

替换字符串中的子串:

lua
local str = "Hello World"
local newStr = str:gsub("World", "Lua")
print(newStr)  -- 输出 Hello Lua

gmatch(pattern)

返回一个迭代器,用于遍历字符串中所有匹配 pattern 的子串:

lua
local str = "Hello World Hello Lua"
for word in str:gmatch("%a+") do
  print(word)
end

输出:

Hello
World
Hello
Lua

lower()

将字符串转换为小写:

lua
local str = "HELLO WORLD"
print(str:lower())  -- 输出 hello world

upper()

将字符串转换为大写:

lua
local str = "hello world"
print(str:upper())  -- 输出 HELLO WORLD

reverse()

反转字符串:

lua
local str = "Hello"
print(str:reverse())  -- 输出 olleH

len()

返回字符串长度:

lua
local str = "Hello"
print(str:len())  -- 输出 5

match(pattern, start)

返回字符串中匹配 pattern 的子串:

lua
local str = "Hello World"
print(str:match("%a+"))  -- 输出 Hello

rep(count)

重复字符串 count 次:

lua
local str = "Hello"
print(str:rep(3))  -- 输出 HelloHelloHello

format(formatstring, ...)

格式化字符串:

lua
local name = "张三"
local age = 30
local str = string.format("姓名:%s,年龄:%d", name, age)
print(str)  -- 输出 姓名:张三,年龄:30

字符串格式化

使用 string.format 函数进行字符串格式化,支持以下格式化选项:

选项描述
%s字符串
%d整数
%f浮点数
%c字符
%x十六进制数
%o八进制数
%e科学计数法
lua
print(string.format("%s", "Hello"))  -- 输出 Hello
print(string.format("%d", 123))  -- 输出 123
print(string.format("%f", 3.14))  -- 输出 3.140000
print(string.format("%c", 65))  -- 输出 A
print(string.format("%x", 255))  -- 输出 ff
print(string.format("%o", 8))  -- 输出 10
print(string.format("%e", 12345))  -- 输出 1.234500e+04

字符串转义字符

转义字符描述
\n换行
\t制表符
\r回车
"双引号
'单引号
\反斜杠
lua
local str = "Hello\nWorld"
print(str)  -- 输出 Hello 后换行,再输出 World

local str2 = "Hello\tWorld"
print(str2)  -- 输出 Hello 后加制表符,再输出 World

local str3 = "He said \"Hello\""
print(str3)  -- 输出 He said "Hello"

字符串操作的性能

在 Lua 中,字符串是不可变的,每次字符串操作都会创建一个新的字符串。因此,对于大量的字符串操作,应该使用 table.concat 来提高性能:

lua
-- 不推荐的方式
local str = ""
for i = 1, 1000 do
  str = str .. i
end

-- 推荐的方式
local t = {}
for i = 1, 1000 do
  t[i] = i
end
local str = table.concat(t)

字符串的应用

示例 1:分割字符串

lua
function split(str, sep)
  local t = {}
  for word in str:gmatch("([^" .. sep .. "]+)") do
    table.insert(t, word)
  end
  return t
end

local str = "Hello,World,Lua"
local parts = split(str, ",")
for i, part in ipairs(parts) do
  print(part)
end

输出:

Hello
World
Lua

示例 2:去除字符串首尾空格

lua
function trim(str)
  return str:gsub("^%s*", ""):gsub("%s*$", "")
end

local str = "  Hello World  "
print("|" .. trim(str) .. "|")  -- 输出 |Hello World|

示例 3:判断字符串是否以某个前缀开头

lua
function startsWith(str, prefix)
  return str:sub(1, #prefix) == prefix
end

local str = "Hello World"
print(startsWith(str, "Hello"))  -- 输出 true
print(startsWith(str, "World"))  -- 输出 false

示例 4:判断字符串是否以某个后缀结尾

lua
function endsWith(str, suffix)
  return str:sub(-#suffix) == suffix
end

local str = "Hello World"
print(endsWith(str, "World"))  -- 输出 true
print(endsWith(str, "Hello"))  -- 输出 false

小结

本章节介绍了 Lua 中字符串的基本操作和常用方法,包括字符串定义、连接、长度、索引、方法、格式化、转义字符和性能优化等内容。掌握这些内容,对于编写 Lua 程序非常重要。