C# 运行包含重复项的文本文件,并用用户输入替换变量

C# 运行包含重复项的文本文件,并用用户输入替换变量,c#,C#,我创建了一个文本文件,看起来有点像这样: Hello <name>! You and <name> will go for a run in the <place>. 你好!你和我将在公园里跑步。 我想用用户输入替换文件中的名称变量,并允许重复。例如,可能在文本文件中出现两次,并且应该能够接受不同的用户答案 任何建议都将不胜感激。 *再问一遍,重新编码 string contents = File.ReadAllText("mad.txt"); Cons

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

Hello <name>! You and <name> will go for a run in the <place>.
你好!你和我将在公园里跑步。
我想用用户输入替换文件中的名称变量,并允许重复。例如,
可能在文本文件中出现两次,并且应该能够接受不同的用户答案

任何建议都将不胜感激。 *再问一遍,重新编码

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);
string contents=File.ReadAllText(“mad.txt”);
控制台。写入(“输入名称:”);
字符串名称=Console.ReadLine();
控制台。写(“输入一个位置:”);
string place=Console.ReadLine();
contents=contents.Replace(“,name”).Replace(“,place);
writealText(“somefile.txt”,contents);
控制台写入线(目录);

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

var name1=Console.ReadLine();
var name2=Console.ReadLine();
File.WriteAllText(“somefile.txt”,File.ReadAllText(“mad.txt”)。
替换(“,名称1)。替换(“,名称2”);

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

然后,您可以选择首先创建一个名称列表,然后搜索第一个出现的文件内容并将其替换为第一个名称,然后将第二个替换为第二个名称,等等

虽然不是很理想,但一种方法是将字符串按
拆分
(这将消除其副作用),然后创建一个新字符串,在该字符串中获取拆分字符串的第一个索引并向其添加第一个名称,然后在拆分字符串的第二个索引中添加第二个名称,等等

注意:你应该自己写代码,否则老师可能会生气……

Regex myreg=newregex(@“);
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();  
}
字符串内容=File.ReadAllText(“mad.txt”); 字符串modifiedContents=内容; 匹配m=myreg.Match(内容);//m是第一场比赛 while(m.Success) { Console.Write(“请输入”+m.Value.Replace(“,”)+“:”); string place=Console.ReadLine(); modifiedContents=myreg.Replace(内容,m.值,位置,1); m=m.NextMatch(); }
这就是您想要的吗?那么您想构建一个模板引擎吗?其他模板引擎有什么问题?@MarcB可能只是出于兴趣。你一小时前就在这里问了这个问题:我编辑了我的问题,没有人回答,所以网站建议你再发一个问题。编码没有考虑到文本文件中的重复变量。他有一个问题,他可以多次使用相同的标记,并且在每个事件中需要不同的值(据我所知,他无法控制标记所在的文件)@Thomas,我刚刚读了他的评论;)我没有看到他^^^的一条评论(只是从问题本身和他提出的另一个问题中得到了这种印象)
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();  
}