替换字符串 C#
本文关键字:字符串 替换 | 更新日期: 2023-09-27 18:30:58
我的字符串为"Date :<#Tag(SystemTagDateTime)> Value1 :
<#Tag(value1)>" 我想将SystemTagDateTime ,value1替换为其值,并希望在消息框中将整个字符串显示为"Date :2016-05-18 10:00:00 Value1 : 10"
我的初始字符串可能有一个或多个<#Tag(任何)>。我已经尝试但未能获得所需的值例如
行 -> 日期 :<#Tag(系统标记日期时间)> 值 1 : <#Tag(值 1)>
string[] values =Regex.Split(line, "<#Tag''(|'')>").Where(x => x != string.Empty).ToArray();
string text = "";
foreach (string val in values) {
if (!(String.IsNullOrEmpty (val.Trim ())))
{
foreach(GlobalDataItem gdi in Globals.Tags.GlobalDataItems)
{
MessageBox.Show(val);
if (gdi.Name == val)
{
text+= gdi.Value;
}
}
}
else
{
text += val ;
}
}
这是解决任务的简单方法:
//Input string and we would like to keep it value
const string str = "Date :<#Tag(SystemTagDateTime)> Value1 : <#Tag(value1)>";
string text = str;
foreach (GlobalDataItem gdi in Globals.Tags.GlobalDataItems)
{
//Preparing tag name. for instance, <#Tag(SystemTagDateTime)>
string tag = string.Format("<#Tag({0})>", gdi.Name);
//Replace the tag everywhere with value from gdi.
text = text.Replace(tag, gdi.Value);
}
在"文本"中,您将拥有字符串。