例如,我有一大块文字
string OriginalText = "Hello my name is <!name!> and I am <!age!> years old";
我正在努力编写一个我可以输入此文本的函数,它将返回相同的字符串,除了使用标签"<!"
和"!>"
包围的值替换为实际值。我写了一些代码,但不知道如何进一步发展。
if(OriginalText.Contains("<!")) //Checks if Change is necessary
{
string[] Total = OriginalText.Split(
new Char[] { '<', '!' },
StringSplitOptions.RemoveEmptyEntries);
if(Total[1].Contains("!>")) //Checks if closing tag exists
{
string ExtTag = Total[1].Split(
new Char[] { '<', '!' },
StringSplitOptions.RemoveEmptyEntries)[0];
ExtData.Add(Total[1].Split(
new Char[] { '<', '!' },
StringSplitOptions.RemoveEmptyEntries)[0]);
return Total[1];
}
}
期望的输出将是
"Hello my name is James and I am 21 years old"
我目前从数据库中获取此文本,因此此功能的目的是读取该文本并输入正确的信息。
编辑:弄清楚如何做到这一点我将在下面包含它但是我在一个名为mattersphere的程序中写这个,所以会引用不是标准c#的函数,我会在它们旁边放置注释解释什么他们是这样。
private string ConvertCodeToExtData(string OriginalText) //Accepts text with the identifying symbols as placeholders
{
string[] OriginalWords = OriginalText.Split(' '); //Creates array of individual words
string ConvertedText = string.Empty;
int Index = 0;
foreach(string OriginalWord in OriginalWords) //Go through each word in the array
{
if(OriginalWord.Substring(0,1).Equals("<") && OriginalWord.Substring(OriginalWord.Length-1 ,1).Equals(">")) //Checks if Change is necessary
{
string[] ExtDataCodeAndSymbols = OriginalWord.Substring(1, OriginalWord.Length-2).Split('.'); //Decided to create 4 different parts inbetween the <> tags it goes Symbol(e.g £, $, #) . area to look . field . symbol //separates the Code Identifier and the ExtData and Code
try
{
foreach(ExtendedData ex in this.CurrentSession.CurrentFile.ExtendedData) //Search through All data connected to the file, Extended data is essentially all the data from the database that is specific to the current user
{
if(ex.Code.ToLower() == ExtDataCodeAndSymbols[1].ToLower())
{
OriginalWords[Index] = ExtDataCodeAndSymbols[0] + ex.GetExtendedData(ExtDataCodeAndSymbols[2]).ToString() + ExtDataCodeAndSymbols[3]; //Replace code with new data
break;
}
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Extended Data Field " + ExtDataCodeAndSymbols[1] + "." + ExtDataCodeAndSymbols[2] + " Not found, please speak to your system administrator"); //Handles Error if Ext Data is not found
}
}
Index++;
}
foreach(string Word in OriginalWords)
{
ConvertedText += Word + " "; //Adds all words into a single string and adds space
}
ConvertedText.Remove(ConvertedText.Length -1, 1); //Removes Last Space
return ConvertedText;
}
文字在“Hello我的名字是<.Person.name。>,我在我的银行帐户中有<.Account.Balance。>”并出来“你好我的名字是詹姆斯,我的银行账户里有100英镑“
符号是可选的,但是“。”是必要的,因为它们用于在函数的早期拆分字符串
如果你必须使用<!...!>
占位符,我建议使用正则表达式:
using System.Text.RegularExpressions;
...
string OriginalText = "Hello my name is <!name!> and I am <!age!> years old";
Dictionary<string, string> substitutes =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
{ "name", "John" },
{ "age", "108"},
};
string result = Regex
.Replace(OriginalText,
@"<!([A-Za-z0-9]+)!>", // let placeholder contain letter and digits
match => substitutes[match.Groups[1].Value]);
Console.WriteLine(result);
结果:
Hello my name is John and I am 108 years old
假设您坚持使用该格式,并假设您提前知道字段列表,则可以编写替换字符串的字典,并将其替换。
//Initialize fields dictionary
var fields = new Dictionary<string, string>();
fields.Add("name", "John");
fields.Add("age", "18");
//Replace each field if it is found
string text = OriginalText;
foreach (var key in fields.Keys)
{
string searchFor = "<!" + key + "!>";
text = text.Replace(searchFor, fields[key]);
}
如果替换字段的值来自域对象,则可以使用反射迭代属性:
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class Program
{
const string OriginalText = "Hello my name is <!name!> and I am <!age!> years old";
public static void Main()
{
var p = new Person();
p.Age = 18;
p.Name = "John";
//Initialize fields dictionary
var fields = new Dictionary<string, string>();
foreach (var prop in typeof(Person).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
fields.Add(prop.Name, prop.GetValue(p).ToString());
}
///etc....
如果您需要标记检查不区分大小写,则可以使用此代替String.Replace()
:
string searchFor = @"\<\!" + key + @"\!\>";
text = Regex.Replace(text, searchFor, fields[key], RegexOptions.IgnoreCase);
我想你正在寻找这个:
var str = string.Format("Hello my name is {0} and I am {1} years old", name, age);
或者,从C#6开始,你可以使用它:
var str = $"Hello my name is {name} and I am {age} years old";