String Formatting

The code in Chapter 1 glazed over the utility of the Console.WriteLine method. Actually this method has some powerful output string formatting capabilities, which are summarized in this section. Listing 2.1 shows a WriteLine method with a format string and parameters.

Listing 2.1 Console.WriteLine Method with Formatted String (HelloTime.cs)
 using System; class HelloTime {    static void Main()    {       string name = "Joe";       Console.WriteLine("Hello, {0}! Today is {1}.",          name, DateTime.Now);       Console.ReadLine();    } } 

The first parameter to WriteLine is a format string with placeholders, identified by numbers surrounded by curly braces. The placeholder numbers begin at 0 and continue, as shown in Listing 2.1, where the first placeholder is {0} and the second is {1}. Parameters following the format parameter replace the placeholders, in order of occurrence, when the formatting occurs at runtime.

There are several more ways to perform string formatting: using the concatenation operator (+) and using the String.Format method. Listing 2.2 shows how to use each of these.

Listing 2.2 More String Formatting (CountDown.cs)
 using System; class CountDown {    static void Main()    {       string countDown = String.Format("{0}, {1}, ...", 10, 9);       Console.WriteLine("countDown = " + countDown);       Console.ReadLine();    } } 

The static Format method of the String type formats strings just like the WriteLine, except that it returns the formatted string rather than printing it to the console. Another means of formatting, which is convenient but less powerful, is the concatenation operator (+).

SHOP TALK
STRING EFFICIENCY

Check out the StringBuilder in the System.Text namespace for working with strings that require multiple concatenations. The concatenation operator, +, is convenient for a quick concatenation but quickly becomes inefficient. You see, the string type is immutable, meaning that it can't be changed. Therefore, every time the + operator is used, it creates a new string object. A good rule of thumb is to start using the StringBuilder after four or more concatenations.



C# Builder KickStart
C# Builder KickStart
ISBN: 672325896
EAN: N/A
Year: 2003
Pages: 165

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net