1. Technology

Formatting Strings, Numbers, and Other Objects

Where Formatting Doesn't Work


Format can't solve all problems, however. When I was reviewing Murach's ADO.NET 4 Database Programming, I found this code to format a telephone number that's stored as a string.

phoneNumOut =
    phoneNumIn.Substring(0, 3) & "." &
    phoneNumIn.Substring(3, 3) & "." &
    phoneNumIn.Substring(6, 4)

My first thought was that Format should be able to do that more elegantly and possibly more efficiently. So I tried to use Format. I discovered that Format couldn't do that more elegantly. (Or, at least I couldn't find a way.) The problem can be found in the Object Browser documentation for Format (using the ToString method in this case), "Returns this instance of System.String; no actual conversion is performed." None of the other versions of Format seem to work on String input either. The best I could do is the slightly in-elegant ...

phoneNumOut =

The "\." syntax "escapes" the period character so it's not interpreted as part of the formatting instruction. I wrote a Stopwatch comparison of the time required for the Murach Substring method versus this method and this method takes just about twice as long, probably because it converts from String to Long and back to String again.

Maybe one of my readers can find a better way. I'll post an update if someone sends one in.

Since I was looking for every possible way to format a String, there is one more that I decided to investigate: Regular Expressions, also known as RegEx. Regular Expressions are difficult to understand unless you work with them long enough. They're nothing like VB expressions. If you need an introduction to RegEx and VB.NET, you can find it here: Regular Expressions in VB.NET.

Regular Expressions are used more often for tasks like validation. You can find pre-written Regular Expressions for a wide variety of tasks like validating virtually any phone number from around the world. Microsoft's implementation of Regular Expressions also has a Replace method, however. With a little testing, I was able to write this Regular Expression to substitute periods into a phone number.

Dim matchPattern As String = "(\d{3})(\d{3})(\d{4})"
Dim replacePattern As String = "$1.$2.$3"
phoneNumOut =
    Regex.Replace(phoneNumIn, matchPattern,
                  replacePattern, RegexOptions.Compiled)

This didn't really solve any problems either. The Stopwatch object measured time to execute this was about five times as much as the Murach Substring method. So Murach was right to begin with!

  1. About.com
  2. Technology
  3. Visual Basic
  4. Using VB.NET
  5. Formatting Strings, Numbers, and Other Objects

©2014 About.com. All rights reserved.