C#
  Home arrow C# arrow Page 3 - 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.15 Converting Strings to Their Equivalent Value Type


    (Page 3 of 11 )

    Problem

    You have a string that represents the equivalent value of a number ("12"), char ("a"), bool ("true"), or a color enumeration ("Red"). You need to convert this string to its equivalent value type. Therefore, the number "12" would be converted to a numeric value such as int, short, float, etc. The string "a" would be converted to a char value 'a', the string "true" would be converted to a bool value, and the color "Red" could be converted to an enumeration value (if an enumeration were defined that contained the element Red).

    Solution

    Use the Parse static method of the type that the string is to be converted to. To convert a string containing a number to its numeric type, use the following code:

    // This code requires the use of the System and System.Globalization namespaces

    string longString = "7654321";
    int actualInt = Int32.Parse(longString); // longString = 7654321

    string dblString = "-7654.321"; double actualDbl = Double.Parse(dblString, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign); // longString = "-7654.321

    To convert a string containing a Boolean value to a Boolean type, use the following code:

    // This code requires the use of the System namespace

    string boolString = "true"; bool actualBool = Boolean.Parse(boolString); // actualBool = true

    To convert a string containing a char value to a char type, use the following code:

    // This code requires the use of the System namespace

    string charString = "t"; char actualChar = char.Parse(charString); // actualChar = 't'

    To convert a string containing an enumeration value to an enumeration type, use the following code:

    // This code requires the use of the System namespace

    enum Colors
    {
    red, green, blue
    }

    string colorString = "blue";
    // Note that the Parse method below is a method defined by System.Enum, not by Colors
    Colors actualEnum = (Colors)Colors.Parse(typeof(Colors), colorString);

    // actualEnum = blue

    Discussion

    The static Parse method on certain types derived from the ValueType data types allows easy conversion from a string value to the value of that specific value type. The Parse method is supported by the following types:

    Boolean     Int64
    Byte         SByte
    Decimal     Single
    Double      UInt16
    Int16        UInt32
    Int32        UInt64

    In addition to the Parse methods that take a single string parameter and convert it to the target data type, each numeric type has a second overloaded version of the Parse method that includes a second parameter of type System.Globalization. NumberStyles. This allows the Parse method to correctly handle specific properties of numbers, such as leading or trailing signs, decimal points, currency symbols, thousands separators, etc. NumberStyles is marked as a flag-style enumeration, so you can bitwise OR more than one enumerated value together to allow a group of styles to be used on the string.

    The NumberStyles enumeration is defined as follows:

    AllowCurrencySymbol

    If the string contains a number with a currency symbol, it is parsed as currency; otherwise, it is parsed as a number.

    AllowDecimalPoint

    Allows a decimal point in the number.

    AllowExponent

    Allows the number to be in exponential notation format.

    AllowHexSpecifier

    Allows characters that specify a hexadecimal number.

    AllowLeadingSign

    Allows a leading sign symbol.

    AllowLeadingWhite

    Ignores any leading whitespace.

    AllowParentheses

    Allows parentheses.

    AllowThousands

    Allows group separators.

    AllowTrailingSign

    Allows a trailing sign symbol.

    AllowTrailingWhite

    Ignores any trailing whitespace.

    Any

    Applies any of the previous styles. This style simply ORs together all of the preceding styles.

    Currency

    Same as the All style, except that the AllowExponent style is omitted.

    Float

    Equivalent to AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign |AllowDecimalPoint | AllowExponent

    HexNumber

    Equivalent to AllowLeadingWhite | AllowTrailingWhite | AllowHexSpecifier

    Integer

    Equivalent to AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign

    None

    Applies none of the styles.

    Number

    Equivalent to AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign |AllowTrailingSign | AllowDecimalPoint | AllowThousands

    If the NumberStyle parameter is not supplied when it is required (as when, for example, a numeric string includes a thousands separator), or if the NumberStyle enumeration is used on a string that does not contain a number in the supplied NumberStyle format, a FormatException exception will be thrown. If the size of the number in the string is too large or too small for the data type, an OverFlowException exception will be thrown. Passing in a null for the SourceString parameter will throw an ArgumentNullException exception.

    The Parse method of the two non-numeric data types, bool and char, also deserve some additional explanation. When calling Boolean.Parse, if a string value contains anything except a value equal to the static properties Boolean.FalseString, Boolean. TrueString, or the string literals "false" or "true" (which are case-insensitive), a FormatException exception is thrown. Passing in a null for the SourceString parameter throws an ArgumentNullException exception.

    When invoking char.Parse, if a string value containing more than one character is passed as its single argument, a FormatException exception is thrown. Passing in a null for the string parameter throws an ArgumentNullException exception.

    The static Enum.Parse method returns an Object of the same type as specified in the first parameter of this method (EnumType). This value is viewed as an Object type and must be cast to its correct enumeration type.

    This method throws an ArgumentException exception if the Value parameter cannot be matched to a string in the enumeration. An ArgumentNullException exception is thrown if a null is passed in to the Value parameter.

    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