假设我有一个包含字符串的 .txt 文件。如何删除某些字符,或在它们之间插入其他字符?示例:.txt 文件包含“HelloWorld”,我想在“Hello”后面插入一个逗号,然后在后面插入一个空格。我只知道如何从头开始写入并附加文件
local file = io.open("example.txt", "w")
file:write("Example")
file.close()
最佳答案
您需要将其分解为不同的步骤。
以下示例将“HelloWorld”替换为“Hello, World”
--
-- Read the file
--
local f = io.open("example.txt", "r")
local content = f:read("*all")
f:close()
--
-- Edit the string
--
content = string.gsub(content, "Hello", "Hello, ")
--
-- Write it out
--
local f = io.open("example.txt", "w")
f:write(content)
f:close()
当然你需要添加错误测试等。
关于Lua - 在 txt 文件中插入或删除字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25071164/