Formatting Strings


Formatting enables you to define templates for strings. The template tells the string class the text that doesn't change. In the template you also specify placeholders for the text that does change. The string class then fills in the placeholders with text that you provide. This makes it easier for you, because the string class does the hard work of concatenating the parts of fixed text with the parts of variable text.

To format strings:

  1. Type string str where str is the name of the string that will hold the formatted text.

  2. Type =string.Format( .

  3. Type a formatting string enclosed in quotes. The formatting string tells the string class the fixed text.

  4. Within the formatting string, type {0} , {1} , {2} , etc. to set placeholders for the variable text. For example: "LastName={0} and FirstName={1}" .

  5. Type a comma.

  6. Type the name of the variable that contains the dynamic text for the string.

  7. Repeat steps 5 and 6 for each placeholder in step 4.

  8. Type ); to end the statement ( Figure 4.56 ).

    Figure 4.56 You can build a format string to serve as a template. In the format string you specify placeholders for each segment. The placeholders are specified with curly brackets.
     string firstName = "Bill"; string lastName = "Smith"; string templ = "Select * from contacts where "; templ += "LastName={0} and FirstName={1}"; string SQL =  string.Format(templ,firstName,lastName);  Response.Write(SQL); /* outputs: Select * from contacts where LastName=Bill and FirstName=Smith */ 

graphics/tick.gif Tip

  • You can use the same placeholder more than once. For example, if you were writing a form letter, you could repeat the recipient's name more than once. To accomplish that you simply use the placeholder string, for example {0} more than once ( Figure 4.57 ).

    Figure 4.57 Each placeholder has an index number. You can insert the same word in many places in the string if you repeat the index number that corresponds to the word.
     string company = "Federation"; string customer = "Chewbacca"; string templ = "Dear Mr.  {1}  ,<br>"; templ += "Welcome to the  {0}  . "; templ += "The  {0}  is glad that you have become "; templ += "a warp capable species."; string letter = string.Format(templ,company,customer); Response.Write(letter); /* outputs: Dear Mr.  Chewbacca  , Welcome to the  Federation  . The  Federation  is glad that you have become a warp capable species. */ 



C#
C# & VB.NET Conversion Pocket Reference
ISBN: 0596003196
EAN: 2147483647
Year: 2003
Pages: 198
Authors: Jose Mojica

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