【问题标题】:How can I search a text file for word and replace it in C#? [duplicate]如何在文本文件中搜索 word 并在 C# 中替换它? [复制]
【发布时间】:2015-11-23 12:12:02
【问题描述】:

我创建了一个看起来有点像这样的文本文件:

Hello <name>! You and <name> will go for a run in the <place>.

我想用用户输入替换文件中的名称变量并允许重复。例如名称可能出现两次,应该能够接受不同的答案。

Console.Write("Enter a name: ");
Console.Write("Enter another name: ")

我意识到我必须搜索文件和括号,但我不知道该怎么做。任何建议表示赞赏。

【问题讨论】:

    标签: c# c#-4.0


    【解决方案1】:

    使用File.ReadAllText() 获取文件的内容,将其替换并保存回来,如下所示:

    string contents = File.ReadAllText("somefile.txt"); //Change this to your file.
    contents = contents.Replace("<name>", nameVariable).Replace("<place>", placeVariable);
    File.WriteAllText("somefile.txt", contents);
    

    您需要导入System.IO 命名空间。

    【讨论】:

    • 这是我想过的,但一个大问题是我的文本文件有重复。 “”变量出现不止一次,应该能够有不同的用户输入答案。
    • 那么你应该在你的问题中提到这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多