简体   繁体   中英

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. 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. 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"

Also, you can try a Dictionary with the key = "[0]" or "[1]", etc and values which you want to see instead of these keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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