Formatting and Styling Strings (C#)
We’ve discussed different ways to format a string using printf for C++ and string.format for Java/Android and since I’ve been working with C# recently I would add that to the blog as well.
In C#, it’s just like Java/Android: use string.Format(). Instead of dollar signs, you would use curly brackets with the parameter number. What’s nice is that you don’t really need to worry about the type. For example:
int foo = 9000;
string bar = "sparta";
string fubar = string.Format("This is {0}! It is over {1}!", bar, foo);
Would result with:
This is sparta! It is over 9000!"
See how I didn’t need to tell it {0} was a string and {1} was an integer? You can also add the format inside the curly bracket if you wish such as:
{index,length:formatString}
Where index is the index of the value to use; length is the amount of spaces you want this variable to take up; and formatString is a standard or custom string that can be used to do more formatting (such as setting up a date in US or EU format).
As usual, if you’d like to know more about the details, visit MSDN for more reading.
