1

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!

2
  • You'll have to use string.Replace e.g. template.Replace("{a}", a).Replace("{b}", b).Replace("{c}", c) Commented Apr 30, 2020 at 3:34
  • Does this answer your question? String Interpolation with format variable This answer might be helpful as well Commented Apr 30, 2020 at 7:39

4 Answers 4

2

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);
Sign up to request clarification or add additional context in comments.

Comments

2

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"

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.