C#
  Home arrow C# arrow Page 4 - Strings and Characters, Part 2
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Strings and Characters, Part 2
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 8
    2004-08-03

    Table of Contents:
  • Strings and Characters, Part 2
  • 2.14 Passing a String to a Method that Accepts Only a Byte[ ]
  • 2.15 Converting Strings to Their Equivalent Value Type
  • 2.16 Formatting Data in Strings Problem
  • 2.17 Creating a Delimited String
  • 2.18 Extracting Items from a Delimited String
  • 2.19 Setting the Maximum Number of Characters a String Can Contain
  • 2.20 Iterating Over Each Character in a String
  • 2.21 Improving String Comparison Performance
  • 2.22 Improving StringBuilder Performance
  • 2.23 Pruning Characters from the Head and/or Tail of a String

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Strings and Characters, Part 2 - 2.16 Formatting Data in Strings Problem


    (Page 4 of 11 )

    You need to format one or more embedded pieces of information inside of a string, such as a number, character, or substring.

    Solution

    The static string.Format method allows you to format strings in a variety of ways. For example:

    int ID = 12345;
    double weight = 12.3558;
    char row = 'Z';
    string section = "1A2C";

    string output = string.Format(@"The item ID = {0:G} having weight = {1:G}

    is found in row {2:G} and section {3:G}", ID, weight, row, section); Console.WriteLine(output);
    output = string.Format(@"The item ID = {0:N} having weight = {1:E}

    is found in row {2:E} and section {3:E}", ID, weight, row, section); Console.WriteLine(output);
    output = string.Format(@"The item ID = {0:N} having weight = {1:N}

    is found in row {2:E} and section {3:D}", ID, weight, row, section); Console.WriteLine(output);
    output = string.Format(@"The item ID = {0:(#####)} having weight = {1:0000.00 lbs}

    is found in row {2} and section {3}", ID, weight, row, section); Console.WriteLine(output);

    The output is as follows:

    The item ID = 12345 having weight = 12.3558 is found in row Z and section 1A2C
    The item ID = 12,345.00 having weight = 1.235580E+001 is found in row Z and section 1A2C
    The item ID = 12,345.00 having weight = 12.36 is found in row Z and section 1A2C
    The item ID = (12345) having weight = 0012.36 lbs is found in row Z and section 1A2C

    To simplify things, the string.Format method could be discarded and all the work could have been done in the System.Console.WriteLine method, which calls string. Format internally, as shown here:

    Console.WriteLine(@"The item ID = {0,5:G} having weight = {1,10:G} " +
    "is found in row {2,-5:G} and section {3,-10:G}",
    ID, weight, row, section);

    The output of this WriteLine method is:

    The item ID = 12345 having weight = 12.3558 is found in row Z and section 1A2C

    Discussion

    The string.Format method allows a wide range of formatting options for string data. The first parameter of this method can be passed a string that may look similar to the following:

    "The item ID = {0,5:G}"

    The text The item ID= will be displayed as is, with no changes. The interesting part of this string is the section enclosed in braces. This section has the following form:

    {index, alignment:formatString}

    The section can contain the following three parts:

    index

    A number identifying the zero-based position of the section’s data in the args parameter array. The data is to be formatted accordingly and substituted for this section. This number is required.

    alignment

    The number of spaces to insert before or after this data. A negative number indicates left justification (spaces are added to the right of the data), and a positive number indicates right justification (spaces are added to the left of the data). This number is optional.

    formatString

    A string indicating the type of formatting to perform on this data. This section is where most of the formatting information usually resides. Tables 2-2 and 2-3 contain valid formatting codes that can be used here. This part is optional.

    Table 2-2. The standard formatting strings

    Formatting character(s) Meaning
    C or c Use the currency format. A precision specifier can optionally follow, indicating the number of decimal places to use.
    D or d Use the decimal format for integral types. A precision specifier can optionally follow, which represents the minimum number of digits in the formatted number.
     
    E or e Use scientific notation. A precision specifier can optionally follow, indicating the number of dig its to use after the decimal point.  
    F or f Use fixed-point format. A precision specifier can optionally follow, which represents the number of digits to display to the right of the decimal point.
    G or g Use the general format. The number is displayed in its shortest form. A precision specifier can optionally follow, which represents the number of significant digits to display.
    N or n Use the number format. A minus sign is added to the beginning of a negative number, and thousands separators are placed accordingly in the number. A precision specifier can optionally follow, which represents the number of digits to display to the right of the decimal point. 
    P or p Use the percent format. The number is converted to a percent representation of itself. A precision specifier can optionally follow, indicating the number of decimal places to use.
    R or r Use the round-trip format. This format allows the number to be formatted to a representation that can be parsed back to its original form by using the Parse method. Any precision specifier is ignored.
     
    X or x Use the hexadecimal format. The number is converted to its hexadecimal representation. The uppercase X produces a hexadecimel number with all capital letters A through F. The lowercase x produces a hexadecimal number with all lowercase letters a through f. A precision specifier can optionally follow, which represents the minimum number of digits in the formatted number.

     

    Table 2-3. Custom formatting strings

    Formatting character(s) Meaning
    0 Use the zero placeholder format. If a digit in the original number exists in this position, display that digit. If there is no digit in the original string, display a zero.
    # Use the digit placeholder format. If a digit in the original number exists in this position, display that digit. If there is no digit in the original string, display nothing.
    . Use the decimal point format. The decimal point is matched up with the decimal point in the number that is to be formatted. Formatting to the right of the decimal point operates on the digits to the right of the decimal point in the original number. Formatting to the left of the decimal  point operates in the same way.
    , Use the thousands separator format. A thousands separator will be placed after every three digits starting at the decimal point and moving to the left. 
     
    % Use the percentage placeholder format. The original number is multiplied by 100 before being displayed.
    E or e Use the scientific notation format. A precision specifier can optionally follow, indicating the
    number of digits to use after the decimal point.
    \ Use the escape character format. The \character and the next character after it are grouped into an escape sequence.
    Any text within single or double quotes such as"aa" or 'aa' Use no formatting; display as is and in the same position in which the text resides in the format string.
    ; Used as a section separator between positive, negative, and zero formatting strings.
    Any other character Use no formatting; display as is and in the same position in which it resides in the format string.

    In addition to the string.Format and the Console.WriteLine methods, the overloaded ToString instance method of a value type may also use the previous formatting characters in Table 2-3. Using ToString, the code would look like this:

    float valueAsFloat = 122.35;

    string valueAsString = valueAsFloat.ToString("[000000.####]");

    The valueAsString variable would contain the formatted number contained in valueAsFloat. The formatted number would look like this:

    [000122.35]

    The overloaded ToString method accepts a single parameter of type IFormatProvider. The IFormatProvider provided for the valueAsFloat.ToString method is a string containing the formatting for the value type plus any extra text that needs to be supplied.

    See Also

    See the “String.Format Method,” “Standard Numeric Format Strings,” and “Custom Numeric Format Strings” topics in the MSDN documentation.

    Buy the book!If you've enjoyed what you've seen here, or to get more information, click on the "Buy the book!" graphic. Pick up a copy today!

    Visit the O'Reilly Network http://www.oreillynet.com for more online content.

    More C# Articles
    More By O'Reilly Media


       · The encoder no longer accepts byte arrays only ubyte arrays so this information is...
     

    C# ARTICLES

    - Cyclic Redundancy Check
    - Handling Methods and Functions
    - Destroying Objects in C#
    - Creating Objects in C-Sharp
    - Classes and Objects
    - Programming Languages: Managed versus Native
    - LINQ-to-MySQL with DbLinq in C#
    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#
    - C# 3.0 Extension Methods





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    Stay green...Green IT