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);
}
CodePudding user response:
The value of your template
parameter will have to change somehow. If you want to use string interpolation, this answer shows that. So
template = $"Hello, {name}";
in which case you wouldn't need to use String.Format
at all. Just make sure you define name
before you define template
.
Or you could use String.Format(template, name);
like you have but you would need template = "Hello, {0}!";
The 0
is the index of the variable that will go in that position. For more info see String.Format
CodePudding user response:
when specifying a format you use an index for the parameters that will follow. It is called a composite format string:
string template = "Hello, {0}!"
this makes it independent of variable names. But the true reason is that the overload of the Format method that you are using takes a params array as parameter as you can see in the method signature:
public static string Format (string format, params object?[] args);
so the index that is found in the template will be applied to extract the objects on the appropriate places from the array of objects that you pass into the method
CodePudding user response:
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")));
CodePudding user response:
If you want to use string.Format()
, the template
must be correct. Add the character $
at the beginning of the template
:
try this:
string name = "Bob";
string template = $"Hello, {name}!";
Console.WriteLine(GetHelloGreeting(template, name)); // Hello, Bob!
public static string GetHelloGreeting(string template, string name)
{
return string.Format(template, name);
}
reult:
Hello, Bob!