Difference between revisions of "Formatting Strings in C Sharp"
(New page: In addition to the wide selection of string manipulation functions outlined in Working with Strings in C#, the string class also provides the ''String.F...) |
(→A Simple C# String Format Example) |
||
Line 16: | Line 16: | ||
<pre> | <pre> | ||
+ | string newString; | ||
+ | |||
+ | newString = String.Format("There are {0} cats in my {1} and no {2}", 2, "house", "dogs"); | ||
+ | |||
+ | System.Console.WriteLine (newString); | ||
</pre> | </pre> | ||
+ | |||
+ | When run, the above code will result in the following output: | ||
+ | |||
+ | <pre> | ||
+ | There are 2 cats in my house and no dogs | ||
+ | </pre> | ||
+ | |||
+ | Let's quickly review the String.Format() method call. The ''format string'' contains 3 place holder indicated by {0}, {1} and {2}. Following the format string are the arguments to be used in each place holder. For example, {0} is replaced by the first argument (the number 2), the {1} by the second argument (the string "house) and so on. | ||
+ | |||
+ | == Using Format Controls == |
Revision as of 15:46, 24 January 2008
In addition to the wide selection of string manipulation functions outlined in Working with Strings in C#, the string class also provides the String.Format() method.
The primary purpose of the C# String.Format() method is to provide a mechanism for inserting string, numerical or boolean values into a string.
The Syntax of the String.Format() Method
The general syntax of the String.Format() method is as follows:
String.Format(format string", arg1, arg2, .... );
The format string is the string into which the values will be placed. Within this string are place holders which indicate the location of each value within the string. Place holders take the form of braces surrounding a number indicating argument to be substituted for the place holder. Following on from the format string is a comma separated list of arguments. There must be an argument for each of the place holders.
A Simple C# String Format Example
The following code fragment demonstrates a very simple use of the String.Format() method:
string newString; newString = String.Format("There are {0} cats in my {1} and no {2}", 2, "house", "dogs"); System.Console.WriteLine (newString);
When run, the above code will result in the following output:
There are 2 cats in my house and no dogs
Let's quickly review the String.Format() method call. The format string contains 3 place holder indicated by {0}, {1} and {2}. Following the format string are the arguments to be used in each place holder. For example, {0} is replaced by the first argument (the number 2), the {1} by the second argument (the string "house) and so on.