1

When using String.Format, you use {0}, {1}, {2}, etc. to reference the variables to place in the string, for example:

string s = String.Format("{0} {1}", "Like", "this.");

Is there any way that I can use string values instead of integers inside the curly braces. So that the input string would be:

"{word1} {word2}"

I am doing this because I have a long text file with areas which need to be filled in. There are too many areas to have an ordered list of variables to place and variables could be repeated.

So how could I use a method similar to String.Format using string names instead of using an index?

Liam Flaherty
  • 337
  • 1
  • 7
  • 19
  • and how would compiler know which parameter goes where? – Kamil Budziewski Jan 15 '14 at 06:51
  • possible duplicate of [named String.Format, is it possible? C#](http://stackoverflow.com/questions/1010123/named-string-format-is-it-possible-c-sharp) and dupe of http://stackoverflow.com/questions/159017/named-string-formatting-in-c-sharp. Please search before posting a question. – Darin Dimitrov Jan 15 '14 at 06:52
  • 2
    There will be one work around but that is not with String.Format. You have to plain copy the string with your keywords and then replace the values using String.Replace() method. – Nil23 Jan 15 '14 at 06:53

2 Answers2

2

This is not possible with String.Format. You can do this:

string result = formatString.Replace("{word1}", replacement);

Suppose you had a dictionary with placeholders as keys and replacements as values, you could do this:

Dictionary<string, string> words = new Dictionary<string, string>();
words["{word1}"] = "Hello";
words["{word2}"] = "World!";

StringBuilder result = new StringBuilder("{word1} {word2}");
foreach (string key in words.Keys)
   result.Replace(key, words[key]);

string finalResult = result.ToString();

I'm using StringBuilder here to make sure that the string is not copied on every Replace, which would be the case if I used string here.

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
1

String.Format does not have this kind of functionality buit-in, how ever you can achieve this by Custom Format strings

Alternatively you can refer the artical Fun With Named Formats, String Parsing, and Edge Cases

Ramashankar
  • 1,598
  • 10
  • 14