Pomster
Pomster

Reputation: 15197

Replace Variables in String?

I am Searching though the contents of a Excel Spreadsheet template at replacing all the variables represented by @Something.

I have all the variables names come up with code, i'm just looking for a way to replace the them in a string.

Example:

My name is @Name

I want it to become:

My name is John.


My Code explained:

I have an array holding a struct which holds:

TagPointer: this is my variable @name, TagValue: this would be the name John

Here i can get the index of where my variable is and i have the original String its Comp. I am just unsure how i can replace the @Something.

int testnum;
if (Comp != "null")
{
    if (Comp.IndexOf(ArrayNode[i].TagPointer) != -1)
    {
        testnum = Comp.IndexOf(ArrayNode[i].TagPointer);                          
    }
}

Upvotes: 1

Views: 19122

Answers (7)

Legolas
Legolas

Reputation: 978

Years later, we now have string interpolation to help with this.

Upvotes: 0

Fermin
Fermin

Reputation: 36071

Unless I'm missing something, can't you use the string.replace function?

You could do something like:

foreach (var tag in ArrayNode)
{
  Comp = Comp.Replace(tag.TagPointer, tag.TagValue);
}

Upvotes: 5

Oliver
Oliver

Reputation: 45071

Have you ever seen the FormatWith extension?

With it you can write something like this:

Status.Text = "{UserName} last logged in at {LastLoginDate}".FormatWith(user);

Upvotes: 5

Kirill Bestemyanov
Kirill Bestemyanov

Reputation: 11964

Do you want this:

string a = "@Something";
a = a.Replace("@somethig", Value);

?

Upvotes: 1

VoonArt
VoonArt

Reputation: 904

Why not using ie

string name = "Giusepe";
string _tmp = "My name is @Name";
_tmp = _tmp.Replace("@Name", name);

Upvotes: 4

npinti
npinti

Reputation: 52185

You could iterate over your array and use the .Contains() to see which tag you have present and use the .Replace() to replace the tag with the actual value.

Upvotes: 2

burning_LEGION
burning_LEGION

Reputation: 13450

use string.Format(), string.Replace() there is less convenient

string value = "John";
string result = string.Format("My name is {0}", value);

Upvotes: 12

Related Questions