Search code examples
c#stringparametersformat

String format template as parameter


I'm beginer in C#. Now I have next task: In method I get template and arguments and I have to return formated string.

For example:

template = "Hello, {name}!"

name = "Bob"

So result must be a string -> Hello, Bob!

public static string GetHelloGreeting(string template, string name)
{
    return string.Format(template, name);
}

Solution

  • String.Format expects an index in the braces. You want to pass the name in it, so you can replace it with the actual name value. I'd suggest to use String.Replace:

    public static string GetHelloGreeting(string template, string name)
    {
        return template.Replace("{name}", name);
    }
    

    You could provide a method which is more reusable. For example:

    public static string ReplaceAll(string template, params (string key, string value)[] replacements)
    {
        foreach (var kv in replacements)
        {
            template = template.Replace("{"+ kv.key + "}", kv.value);
        }
    
        return template;
    }
    

    Your example:

    string res = ReplaceAll("Hello, {name}!", ("name", "Bob"));
    

    but also possible with multiple parameters:

    string res = ReplaceAll("Hello, {name}! Now it's {time}", ("name", "Bob"), ("time", DateTime.Now.ToString("HH:mm")));