[英]C# Run through a textfile with placeholders and replace placeholders with user input
因此,我的文本文件將帶有諸如“嗨,我的名字是[0],我就讀於[1] ...”之類的內容,依此類推,其數量在增加。 在占位符處,我想用用戶輸入替換占位符。
我已經看過之前的問題,但是找不到有效整合用戶輸入的問題。
到目前為止的代碼
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;
當我嘗試加載文本文件時,由於Console.ReadLine()
部分中的錯誤而導致崩潰。 我假設我需要一個循環來遍歷文本文件中的文本,以找到每個占位符並請求用戶輸入,但是我不確定如何解決這個問題。
讓我知道事情的后續
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);
我認為這種方法應該可以幫助您:
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”
另外,您可以嘗試使用鍵=“ [0]”或“ [1]”等,而不是這些鍵來查看想要的值的字典。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.