.
。
lualocal str = "Hello, " str = str .. "World!" -- 创建一个新的字符串并将其赋值给str print(str) -- 输出 "Hello, World!"[[
和]]
可以定义多行字符串,不需要转义字符。
lualocal multilineString = [[ This is a multiline string. It can contain multiple lines of text. No need for escape characters. ]] print(multilineString)Lua提供了一些基本的字符串操作函数,它们都包含在string
库中。
string.len(s)
:返回字符串s
的长度。string.sub(s, i, j)
:返回字符串s
从i
到j
的子串。string.find(s, pattern)
:搜索字符串s
中第一次出现的模式pattern
。string.match(s, pattern)
:搜索字符串s
中第一次出现的模式pattern
,并返回匹配的部分。string.gsub(s, pattern, repl)
:在字符串s
中替换所有匹配模式pattern
的子串为repl
。假设我们要创建一个简单的文本编辑器,用户可以输入多行文本,然后我们可以对这些文本进行一些基本操作,如计算长度、查找特定单词等。
lua-- 读取用户输入的多行文本
local text = io.read("*a") -- 读取整行,包括空格和换行符
-- 显示文本长度
print("Text length: " .. string.len(text))
-- 查找特定单词
local wordToFind = "Lua"
local first, last = string.find(text, wordToFind)
if first then
print("Word '" .. wordToFind .. "' found at position: " .. first)
else
print("Word '" .. wordToFind .. "' not found.")
end
-- 替换文本中的单词
local newWord = "Programming Language"
local replacedText = string.gsub(text, wordToFind, newWord)
print("Text after replacement:")
print(replacedText)
在这个示例中,我们首先读取用户输入的多行文本,然后计算并显示文本的长度。接着,我们查找文本中第一次出现的单词"Lua",并显示其位置。最后,我们将文本中所有出现的"Lua"替换为"Programming Language",并显示替换后的文本。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。