0

I'm trying to replace all double quotes in a file but when I try to update the string array I just get the original line again instead of the cleaned string. (The Boolean's in the ReplaceQuotes function are just for testing and they come back true when there's a " in the line). If I look at the cleanLine string, the quotes have been removed, but when I return the fileContent array, it looks just like the original with the quotes.

 Private Sub CleanFile(currentFileInfo As FileInfo)
    Dim fullName As String = currentFileInfo.FullName
    Dim fileContent As String() = GetFileContent(currentFileInfo.FullName)
    Dim cleanFileContent As String() = ReplaceQuotes(fileContent)
End Sub

Private Function GetFileContent(fileName As String) As String()
    Return System.IO.File.ReadAllLines(fileName)
End Function

Private Function ReplaceQuotes(fileContent As String())

    For Each line As String In fileContent
        Dim cleanLine As String
        Dim quoteTest As Boolean
        quoteTest = line.Contains("""")
        Dim quoteTest2 As Boolean = line.Contains(ControlChars.Quote)
        cleanLine = line.Replace(ControlChars.Quote, "")
        line = cleanLine
    Next

    Return fileContent

End Function
4
  • strings are immutable. you have to reassign it in your array. Commented Jan 6, 2015 at 15:15
  • turn on Option Strict for starters, your function is just returning the stuff it was passed not the processed data; Return fileContent is just what was passed to it. Commented Jan 6, 2015 at 15:15
  • @DanielA.White: this is not related to string's immutability but to the difference between variables and the objects they reference. line is just a local variable which references the string in the array. By re-assigning a new string to that variable you don't change the array. Commented Jan 6, 2015 at 15:19
  • I thought I was reassigning it by doing the line = cleanline but it wasn't working. See Tim's answer below which works. Commented Jan 6, 2015 at 16:05

1 Answer 1

2

You have to re-assign the new strings in the original array instead of replacing the local string variables. Therefore you can't use a For Each but only a For-loop. And the method can be shorter:

Private Sub ReplaceQuotes(fileContent As String())
    For i As Int32 = 0 To fileContent.Length - 1
        fileContent(i) = fileContent(i).Replace(ControlChars.Quote, "")
    Next
End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

It worked. Exactly what I was trying to do (but yours actually works) It makes sense now, I didn't realize the line variable was just a reference to the string and not the actual string itself. Thanks for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.