【问题标题】:Run through a text file w/ duplicates and replace variables with user input [duplicate]运行带有重复项的文本文件并用用户输入替换变量[重复]
【发布时间】:2015-11-23 14:05:02
【问题描述】:

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

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

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

感谢任何建议。 *再次询问/重新措辞

string contents = File.ReadAllText("mad.txt"); 
Console.Write("Enter a name: ");
string name = Console.ReadLine();
Console.Write("Enter a place: ");
string place = Console.ReadLine();
contents = contents.Replace("<name>", name).Replace("<place>", place);
File.WriteAllText("somefile.txt", contents);
Console.WriteLine(contents);

【问题讨论】:

  • 那么你想要构建一个模板引擎?已经可用的大量其他模板引擎有什么问题?
  • @MarcB 也许只是出于兴趣。
  • 一小时前你已经在这里问过这个问题了:stackoverflow.com/questions/33870820/…
  • 我编辑了我的问题,但没有人回复,因此该网站建议您发布另一个问题。编码不考虑文本文件中的重复变量。

标签: c#


【解决方案1】:
Regex myreg = new Regex(@"<w+>");

string contents = File.ReadAllText("mad.txt"); 
string modifiedContents = contents;

Match m = myreg.Match(contents);   // m is the first match
while (m.Success)
{
     Console.Write("Please type in " + m.Value.Replace("<", "").Replace(">", "") + ": ");
     string place = Console.ReadLine();

     modifiedContents = myreg.Replace(contents, m.Value, place, 1);

     m = m.NextMatch();  
}

【讨论】:

    【解决方案2】:

    最简单的方法是为预定义数量的名称提供唯一的占位符(在下面的示例中它只有 2 个,您可以制作更多):

    var name1 = Console.ReadLine();
    var name2 = Console.ReadLine();
    File.WriteAllText("somefile.txt", File.ReadAllText("mad.txt").
        Replace("<name1>", name1).Replace("<name2>", name2));
    

    以不同的方式命名它们是理想的,但教师不允许这样做

    那么您的选择是首先创建一个名称列表,然后在文件内容中搜索第一个匹配项并将其替换为第一个名称,然后用第二个名称替换第二个,等等。

    不是非常理想,但一种方法是通过"&lt;name&gt;"Split 字符串(这将作为副作用消除)然后只需创建一个新字符串,您将在其中获取拆分字符串的第一个索引并首先添加为其命名,然后是拆分的第二个索引并添加第二个名称等。

    P.S.:你应该自己写代码,否则老师可能会生气......

    【讨论】:

    • 他的问题是他可以多次拥有相同的标签,并且希望在每次出现时都有不同的值(据我了解,他无法控制标签所在的文件)
    • @Thomas,我刚刚看了他的评论;)
    • 我没有看到他的一条评论^^(只有问题本身和他提出的另一个问题才有这种印象)
    猜你喜欢
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2013-02-20
    • 2013-11-01
    • 1970-01-01
    • 2020-03-22
    相关资源
    最近更新 更多