Search code examples
stringvb.nettrim

How can I trim double quotes from the start and end of a string in VB?


I receive a string which sometimes has double-quotes at the start and/or end. I need the string without the quotes. I tried following the C# code in this question, but that doesn't compile:

Imports System

Module Program
    Sub Main(args As String())
        Dim text As String = """Text"""
        Console.WriteLine("Original value: " & text)

        Dim trimmed As String = text.Trim('"')
        Console.WriteLine("Trimmed value: " & trimmed)
    End Sub
End Module

Without the last two lines, this prints:

Original value: "Text"

I want the final code to print:

Original value: "Text"
Trimmed value: Text

The compile-time error I receive is:

Program.vb(9,55): error BC30198: ')' expected.

(Line 9 is the Trim call.)

How should I change my code to compile and trim the quotes?


Solution

  • In C#, " doesn't need to be escaped in character literals.

    The syntax for VB character literals is a bit different. It's like a string literal, but with a C suffix. To use a double-quote, you need to double it in the character literal, just like in the string literal. Here's your original example, but fixed:

    Imports System
    
    Module Program
        Sub Main(args As String())
            Dim text As String = """Text"""
            Console.WriteLine("Original value: " & text)
            
            Dim trimmed As String = text.Trim(""""C)
            Console.WriteLine("Trimmed value: " & trimmed)
            
        End Sub
    End Module
    

    The output is now as desired.

    Note that this won't help with double-quotes within the string though, as Trim only looks at the start and end. To remove all double-quotes, you should use String.Replace instead. Here's an example:

    Imports System
    
    Module Program
        Sub Main(args As String())
            Dim text As String = """Before middle quote""After middle quote"""
            Console.WriteLine("Original value: " & text)
    
            Dim trimmed As String = text.Trim(""""C)
            Console.WriteLine("Trimmed value: " & trimmed)
    
            Dim replaced As String = text.Replace("""", "")
            Console.WriteLine("Replaced value: " & replaced)
        End Sub
    End Module
    

    Output:

    Original value: "Before middle quote"After middle quote"
    Trimmed value: Before middle quote"After middle quote
    Replaced value: Before middle quoteAfter middle quote
    

    Of course, you could replace the double-quote with a string, or a single quote instead.