user2114189
user2114189

Reputation: 450

C# Format String

C# can format a string e.g. $"string {a} {b} {c}" to substitute the variables a, b and c into the string.

    var a = "string1";
    var b = "string2";
    var c = "string3";
    var d = $"string {a} {b} {c}";    // become "string string1 string2 string3"

Is is possible to store the format string to a variable so that I can create the string template dynamically.

    var a = "string1";
    var b = "string2";
    var c = "string3";
    var template = "string {a} {b} {c}";

    var d = $template;  // Can I do this?

Thank you!

Upvotes: 1

Views: 318

Answers (4)

tmaj
tmaj

Reputation: 34947

I think a good candidate is string.Format, but you could also use the fancy FormattableStringFactory.

var a = "string1";
var b = "string2";
var c = "string3";
var template = "string {0} {1} {2}"; //Please note, not {a}, but {0}

var str = string.Format(template, a, b, c); // Preferred

// From System.Runtime.CompilerServices
var str2 = FormattableStringFactory.Create(template, new object[] { a, b, c });

If you want to keep '{a}' (not '{0}') then string.Replace is here to help.

var d = template
       .Replace('{a}', a);
       .Replace('{b}', b);
       .Replace('{c}', c);

Upvotes: 1

gMoney
gMoney

Reputation: 235

yes very possible you are taking one string and formatting it to fill in variables just like with any language.

In C# it can be done like this

var a = "string1"; // first string
var b = "string2"; // second string
var c = "string3"; // third string
var d = "string {0} {1} {2}"; // string to format (fill with variables)

// formatting the string 
var template = string.Format(d, a, b, c);

// output -> "string string1 string2 string3"

Upvotes: 2

Hadi Samadzad
Hadi Samadzad

Reputation: 1540

You can implement this by using String.Format.

var a = "string1";
var b = "string2";
var c = "string3";
var template = "string {0} {1} {2}";

var d = String.Format(template, a,b,c);

Upvotes: 1

Alexander Petrov
Alexander Petrov

Reputation: 14231

You should use string.Format:

var a = "string1";
var b = "string2";
var c = "string3";

var template = "string {0} {1} {2}";

var d = string.Format(template, a, b, c);

Upvotes: 2

Related Questions