Recipe 5.25. Parsing Strings


You want to convert string data to several types of numeric or date/time variables in a consistent way.


Sample code folder: Chapter 05\ParseString

Use the Parse() method provided by all types of variables in Visual Basic 2005.


The Parse() method is the counterpart to each object's ToString() method. That is, the string created by calling an object's ToString() method will always be in a for-mat suitable for converting back to the same type of object using its Parse() method. A few examples can help clarify this:

 Dim doubleParse As Double = Double.Parse("3.1416") Dim ushortParse As UShort = UShort.Parse("65533") Dim dateParse As Date = Date.Parse("December 25, 2007") MsgBox(String.Format( _    "doubleParse: {0}{3}ushortParse: {1}{3}dateParse: {2}", _    doubleParse, ushortParse, dateParse, vbNewLine)) 

As shown in Figure 5-28, the data items are stored in the variables as expected when they are parsed.

Figure 5-28. Converting string data to numeric and date/time formats

In many cases, you might want to first check the string to make sure it can be parsed to the desired type of variable before making any attempt to do so. For example, use the IsDate() function to test a string to make sure it can be converted successfully before calling a Date variable's Parse() method to parse the date from the string. If the string is not convertible to the indicated data type, an exception will occur.

See Also

Recipe 5.22 discusses additional content-verification methods.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: