Lua-在txt文件中插入或删除字符串 [英] Lua - Insert or Delete String in txt file

查看:824
本文介绍了Lua-在txt文件中插入或删除字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含字符串的.txt文件.如何删除某些字符,或在它们之间插入其他字符?示例:.txt文件包含"HelloWorld",我想在"Hello"之后插入一个逗号,并在其后插入一个空格.我只知道如何从头开始写并附加文件

Let's say I have a .txt file that contains a string. How can I delete some characters, or insert others between them? Example: .txt file contains "HelloWorld" and I want to insert a comma after "Hello" and a space after that. I only know how to write from start and append a file

local file = io.open("example.txt", "w")
file:write("Example")
file.close()

推荐答案

您需要将其分解为不同的步骤.

You need to break this down into distinct steps.

以下示例将"HelloWorld"替换为"Hello,World"

The following example replaces "HelloWorld" with "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()

当然,您需要添加错误测试等.

Of course you need to add error-testing, etc.

这篇关于Lua-在txt文件中插入或删除字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆