Search code examples
c#string-interpolation

Replace text inside string


I have a string with the following text and I need to substitute several characters:

zpl = "Test text {A1} - test text {A2} - test text {A3}";

I want to replace the {A?} with a value from a Datatable. This works fine for me with Visual Studio 2017, but the 2012 with which I have to compile tells me unexpected character $:

for (int i = 1; i <= 3; i++)
{
    zpl = zpl.Replace($"{{A{i}}}", row[0][i].ToString());
}

I don't know how to make it work with Studio 2012.


Solution

  • $"{{A{i}}}"
    

    (which is new in C#6) is the same as

    string.Format("{{A{0}}}", i)
    

    So your code becomes

    for (int i = 1; i <= 3; i++)
    {
        zpl = zpl.Replace(string.Format("{{A{0}}}", i), row[0][i].ToString());
    }