Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "String.Format" that can accept named input parameters instead of index placeholders? [duplicate]

This is what I know

str = String.Format("Her name is {0} and she's {1} years old", "Lisa", "10"); 

But I want something like

str = String("Her name is @name and she's @age years old"); str.addParameter(@name, "Lisa"); str.addParameter(@age, 10); 
like image 689
Polamin Singhasuwich Avatar asked Apr 21 '16 04:04

Polamin Singhasuwich


People also ask

How do you replace a placeholder in a string?

You can easily use it to replace placeholders by name with this single method call: StringUtils. replaceEach("There's an incorrect value '%(value)' in column # %(column)", new String[] { "%(value)", "%(column)" }, new String[] { x, y });

What is the string .format method used for?

The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.

What is a composite string?

A composite format string consists of zero or more runs of fixed text intermixed with one or more format items. The fixed text is any string that you choose, and each format item corresponds to an object or boxed structure in the list.

What is the string .format method used for in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.


2 Answers

In C# 6 you can use string interpolation:

string name = "Lisa"; int age = 20; string str = $"Her name is {name} and she's {age} years old"; 

As Doug Clutter mentioned in his comment, string interpolation also supports format string. It's possible to change the format by specifying it after a colon. The following example will output a number with a comma and 2 decimal places:

var str = $"Your account balance is {balance:N2}" 

As Bas mentioned in his answer, string interpolation doesn't support template string. Actually, it has no built in support for that. Fortunately it exists in some great libraries.


SmartFormat.NET for example has support for named placeholder:

Smart.Format("{Name} from {Address.City}, {Address.State}", user)  // The user object should at least be like that   public class User {     public string Name { get; set; }     public Address Address { get; set; } }  public class Address {     public string City { get; set; }     public string State { get; set; } } 

It is available on NuGet.


Mustache is also a great solution. Bas has described its pros well in his answer.

like image 77
Fabien ESCOFFIER Avatar answered Oct 13 '22 00:10

Fabien ESCOFFIER


If you don't have C#6 available in your project you can use Linq's .Aggregate():

    var str = "Her name is @name and she's @age years old";      var parameters = new Dictionary<string, object>();     parameters.Add("@name", "Lisa");     parameters.Add("@age", 10);      str = parameters.Aggregate(str, (current, parameter)=> current.Replace(parameter.Key, parameter.Value.ToString())); 

If you want something matching the specific syntax in the question you can put together a pretty simple class based on Aggregate:

public class StringFormatter{      public string Str {get;set;}      public Dictionary<string, object> Parameters {get;set;}      public StringFormatter(string p_str){         Str = p_str;         Parameters = new Dictionary<string, object>();     }      public void Add(string key, object val){         Parameters.Add(key, val);     }      public override string ToString(){         return Parameters.Aggregate(Str, (current, parameter)=> current.Replace(parameter.Key, parameter.Value.ToString()));     }  } 

Usable like:

var str = new StringFormatter("Her name is @name and she's @age years old"); str.Add("@name", "Lisa"); str.Add("@age", 10);  Console.WriteLine(str); 

Note that this is clean-looking code that's geared to being easy-to-understand over performance.

like image 24
Chakrava Avatar answered Oct 12 '22 23:10

Chakrava