We in c # have the ability to form a string by pattern: string s = string.Format("Это текст: {0}", txt); or in the new version of string s = $"Это текст: {txt}"

How to make it possible to create a similar template for the user, and then use it in the code already?

For example:

 string Name = "Максим"; string Age = "31"; string Street = "Красная"; 

The user in the Textbox sets the output template: "{Имя} живет на улице {Улица}" As a result, it should turn out: "Максим живет на улице Красная" That is, instead of {Name} I substitute Name, instead of {Street} - Street.

  • only through Replace to disassemble what the user has entered and substitute - Grundy
  • probably make a sort of dictionary - MaximK
  • @Grundy are you sure? I used to like the course. The old version is pavel
  • @pavel, maybe I just did not understand what the user will enter and how it will be used later - Grundy
  • one
    Maybe it will help: ru.stackoverflow.com/questions/564003 If it helps, tell me, we will close this question as a duplicate. - andreycha

2 answers 2

The first parameter of the string.Format function is a regular string. No matter where it comes from: from a variable, or from a literal string.

It is only important that the number of parameters used in the template be no more than the number of parameters passed to the string.Format function.

Therefore, it is possible to allow the user to enter a template, which will then be used in this function, the problem will be only in checking how many parameters the user uses in his template, and passing the corresponding parameters in the code when calling.

In the case of string interpolation, it is impossible to use, since this record is converted to the same call to string.Format at compile time.

    I did it like this.

     static void Main(string[] args) { string inputString = "{Name}. Возраст {Age}. Живет по адресу {Adress}"; TestClass test = new TestClass() { Name="Max", Adress="Krymsk", Age=31}; Dictionary<string, Object> dict = new Dictionary<string, object>(); dict.Add("{Name}", test.Name); dict.Add("{Age}", test.Age); dict.Add("{Adress}", test.Adress); Console.WriteLine(FormattedString(inputString, dict)); Console.ReadKey(); } public static string FormattedString(string pattern, Dictionary<string, object> values) { string resultStr = pattern; foreach (var keyVal in values) { int idx = resultStr.IndexOf(keyVal.Key, StringComparison.OrdinalIgnoreCase); if ( idx > -1) { string tmp = resultStr.Substring(idx, keyVal.Key.Length); resultStr = resultStr.Replace(tmp, keyVal.Value.ToString()); } } return resultStr; }