Parth Desai
Parth Desai

Reputation: 209

Replace String C#

I am having my string as "Date :<#Tag(SystemTagDateTime)> Value1 : <#Tag(value1)>" I want to replace SystemTagDateTime , value1 by its value and want to show whole string in Message Box as "Date :2016-05-18 10:00:00 Value1 : 10"

My Initial string may have one or more than one <#Tag(Anything)>.I have tried but failed to get desired value For Example

line -> Date :<#Tag(SystemTagDateTime)> Value1 : <#Tag(value1)>

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 ;
    } 
}

Upvotes: 0

Views: 95

Answers (1)

Anatoly
Anatoly

Reputation: 76

This is a simple way how to resolve your task:

//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); 
}

In 'text'you'll have your string.

Upvotes: 2

Related Questions