C# String Formatting: string.Format Guide
In C#, you can use the string.Format method to format strings. This method takes a format string and a series of parameters, and then formats these parameters according to the specifications of the format string.
For example, here is a simple illustration:
int number = 42;
string name = "Alice";
string formattedString = string.Format("Hello, {0}! Your favorite number is {1}.", name, number);
Console.WriteLine(formattedString);
In the example above, we used the string.Format method to format name and number into a string, resulting in Hello, Alice! Your favorite number is 42.
In the string.Format method, the format string can contain placeholders {0}, {1}, {2}, etc., corresponding to the first, second, third parameters in the argument list, and so on. Different format specifiers can be used to specify the output format, for example, {0:C} formats the first parameter as currency.
In C#, besides using the string.Format method, you can also use string interpolation to format strings, for example:
string formattedString = $"Hello, {name}! Your favorite number is {number}.";
Console.WriteLine(formattedString);
This method is relatively more concise and straightforward, but it may not be convenient to use in certain specific situations.