Internet Engineer
Internet Engineer

Reputation: 2534

Replace Double Double Quotes

I need to replace double double quotes but not replace fields with empty values.

Question: How can I replace double double quotes and not replace empty columns?


Original Line

""COTTAGE"","PENNINGTON, NJ","","123456789"

Expected outcome

"COTTAGE","PENNINGTON, NJ","","123456789"


I have created a class that will do the trick, but it replaces all double double quotes, including the empty field:


My code outcome

"COTTAGE","PENNINGTON, NJ",","123456789"

as you can see my code fixes COTTAGE, but kills the empty column after ,NJ to have a single double quote.


Public Class FixFileErrors

Public Shared Sub RemoveDoubleDoubleQuotes(ByVal FilePathandName As String)

    Dim OriginalFile, RevisedFile, LineofText As String

    OriginalFile = FilePathandName
    RevisedFile = Replace(OriginalFile, ".txt", "revised.txt")


    Dim srFileReader As System.IO.StreamReader
    srFileReader = System.IO.File.OpenText(OriginalFile)
    'Dim srFileWritter As System.IO.StreamWriter
    Dim srFileWritter As New System.IO.StreamWriter(RevisedFile)


    Do Until srFileReader.EndOfStream
        LineofText = srFileReader.ReadLine
        LineofText = ReplaceDoubleDoubleQuotes(LineofText)
        srFileWritter.WriteLine(LineofText)
        LineofText = Nothing
    Loop

End Sub

Public Shared Function ReplaceDoubleDoubleQuotes(ByVal Line As String) As String
    Dim NewLine As String


    Dim strFindText As String = Chr(34) & Chr(34)
    Dim strReplaceText As String = Chr(34)

    NewLine = Replace(Line, strFindText, strReplaceText)


    Return NewLine

End Function

End Class

Upvotes: 2

Views: 10186

Answers (1)

Meta-Knight
Meta-Knight

Reputation: 17845

Public Shared Function ReplaceDoubleDoubleQuotes(ByVal Line As String) As String
    Dim NewLine As String

    Dim doubleDoubleQuotes As String = Chr(34) & Chr(34)
    Dim doubleQuote As String = Chr(34)

    'Your original replacement
    NewLine = Replace(Line, doubleDoubleQuotes, doubleQuote)

    'Replacement to fix double-quotes between commas
    NewLine = Replace(NewLine, "," & doubleQuote & ",", "," & doubleDoubleQuotes & ",")

    Return NewLine

End Function

Upvotes: 2

Related Questions