Tuesday, June 12, 2007

Working with double quotes (") in VB.Net

String manipulation in VB2005 is fairly simple. However, things can get a little tricky with the double quote character. How do you look for it in a string? How can you insert into a string? How do you remove it from a string? These are questions that may lead to confusion if you don't know what you're looking for.

Ironically enough, in VB the double quote can also be used as an escape character when searching for it in a string. For example:

Dim strTest As String
strTest = """123""" 'Displays "123" (double quotes appear in the final result)
strTest = """""123""" 'Displays ""123" (double quotes appear in the final result)
strTest = "test\""test" 'Displays test\"test
strTest = "test""test" 'Displays test"test


In cases where you want to insert a double quote character, simply reference it unicode character designation, chr(34). For example:

strTest = Chr(34) 'Displays "


Switching gears for a moment, ever wonder what would the result be if used nested string functions. Consider the following example:

strTest = strTest.Replace("""", "").Replace("""", "X") 'Displays testtest; executes functions from left to right