当前位置:   article > 正文

Lua 字符串

Lua 字符串

在 Lua 中,字符串是一种非常常用的数据类型,用于表示文本。Lua 支持多种字符串操作和格式化选项。以下是 Lua 中字符串的一些基本概念和用法:

创建字符串

字符串可以使用单引号 '...' 或双引号 "..." 来创建。

示例
local str1 = 'Hello, Lua!'
local str2 = "Welcome to the Lua language."
  • 1
  • 2

字符串拼接

字符串可以通过 .. 运算符进行拼接。

示例
local greeting = 'Hello'
local name = 'Alice'
local message = greeting .. ', ' .. name .. '!'
print(message)  -- 输出 "Hello, Alice!"
  • 1
  • 2
  • 3
  • 4

字符串索引

Lua 中的字符串索引是从 1 开始的。

示例
local str = "Hello, Lua!"
print(str:sub(1, 5))  -- 输出 "Hello"
  • 1
  • 2

字符串长度

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

示例
local str = "Hello, Lua!"
print(#str)  -- 输出 12
  • 1
  • 2

字符串操作

Lua 提供了一系列字符串操作函数,位于 string 库中。

常用的字符串函数
  • string.len(s):返回字符串的长度。
  • string.lower(s):将字符串转换为小写字母。
  • string.upper(s):将字符串转换为大写字母。
  • string.sub(s, i, j):返回字符串的子串。
  • string.find(s, pattern[, init[, plain]]):搜索模式出现的位置。
  • string.gsub(s, pattern, repl[, n]):全局替换模式。
示例
local str = "Hello, Lua!"

print(string.len(str))       -- 输出 12
print(string.lower(str))     -- 输出 "hello, lua!"
print(string.upper(str))     -- 输出 "HELLO, LUA!"
print(string.sub(str, 7, 10))-- 输出 "Lua"
print(string.find(str, "Lua"))-- 输出 7
print(string.gsub(str, "o", "*")) -- 输出 "Hell*, L*u*a!"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

格式化字符串

Lua 提供了 string.format 函数来格式化字符串。

示例
local name = "Alice"
local age = 25
local formatted = string.format("%s is %d years old.", name, age)
print(formatted)  -- 输出 "Alice is 25 years old."
  • 1
  • 2
  • 3
  • 4

字符串模式匹配

Lua 支持正则表达式的子集,称为模式。模式匹配可以使用 string.matchstring.find 函数。

示例
local str = "The price is $100."

-- 使用 string.match
local match = string.match(str, "The price is $%d+.")
print(match)  -- 输出 "The price is $100."

-- 使用 string.find
local start, endPos = string.find(str, "$%d+")
print(start, endPos)  -- 输出 14 17
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

示例:字符串反转

下面是一个简单的示例,展示如何使用 Lua 的字符串操作来反转一个字符串。

function reverseString(s)
    local reversed = ""
    for i = #s, 1, -1 do
        reversed = reversed .. string.sub(s, i, i)
    end
    return reversed
end

local str = "Hello, Lua!"
print(reverseString(str))  -- 输出 "!auL ,olleH"
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

示例:字符串搜索

下面是一个示例,展示了如何使用 string.find 来搜索字符串中的模式。

local str = "This is a sample text with some words."
local word = "sample"

local found, startPos = string.find(str, word)
if found then
    print("Found '" .. word .. "' at position " .. startPos)
else
    print("'" .. word .. "' not found.")
end
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

这些是 Lua 中字符串的基本概念和用法。如果您需要更详细的解释或有其他问题,请随时提问!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/963930
推荐阅读
相关标签
  

闽ICP备14008679号