简体   繁体   English

C#在带有占位符的文本文件中运行,并用用户输入替换占位符

[英]C# Run through a textfile with placeholders and replace placeholders with user input

So my text file will have something like this "Hi, my name is [0], and I study at [1]..." and so on, with the number increasing. 因此,我的文本文件将带有诸如“嗨,我的名字是[0],我就读于[1] ...”之类的内容,依此类推,其数量在增加。 At the placeholder, I want to replace the placeholder with user input. 在占位符处,我想用用户输入替换占位符。

I've looked at previous questions, but I can't find one that integrates user input effectively. 我已经看过之前的问题,但是找不到有效整合用户输入的问题。

Code so far- 到目前为止的代码

string input = File.ReadAllText(openFileDialog.FileName);
textBox1.Text = input;
string result = Regex.Replace(input, "[0-9]", Console.ReadLine());
string result2 = result.Replace("[", string.Empty).Replace("]", string.Empty);
textBox2.Text = result2;

It crashes when I try to load my text file due to an error in the Console.ReadLine() part. 当我尝试加载文本文件时,由于Console.ReadLine()部分中的错误而导致崩溃。 I'm assuming I need a loop to iterate through the text in the text file to find each placeholder and ask for user input, but I'm not sure how to work that out. 我假设我需要一个循环来遍历文本文件中的文本,以找到每个占位符并请求用户输入,但是我不确定如何解决这个问题。

Let me know how it goes 让我知道事情的后续

string input = File.ReadAllText(openFileDialog.FileName);
//Hi, my name is {0} and I study at {1}...
textBox1.Text = input;
//Get your name and school here
var name = "";
var school = ""
textBox2.Text = string.Format(input, name, school);

I think this method should help you: 我认为这种方法应该可以帮助您:

public static string AdjustString(string str, List<string> userInput)
{
    int i = 0;
    foreach (var input in userInput)
    {
        var searchedSubstring = $"[{i}]";
        str = str.Replace(searchedSubstring, input);
        i++;
    }
    return str;
}

static void UsgeExample()
{
    var newString = AdjustString("[0][1][2]123[3]",
        new List<string> {"A", "B", "C", "D"});
}

newString = "ABC123D" newString =“ ABC123D”

Also, you can try a Dictionary with the key = "[0]" or "[1]", etc and values which you want to see instead of these keys. 另外,您可以尝试使用键=“ [0]”或“ [1]”等,而不是这些键来查看想要的值的字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM