Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the string replace function in VB.net not work?

Tags:

vb.net

I wrote up some code. The code is shown below. The first part is to read a html into string format. The second part is to search a mark in the string and replace the string by other string.

The 1st part (I test it many times, it works fine)

Public Function ReadTextFile(ByVal TextFileName As String) As String
    Dim TempString As String
    Dim StreamToDisplay As StreamReader
    StreamToDisplay = New StreamReader(TextFileName)
    TempString = StreamToDisplay.ReadToEnd
    StreamToDisplay.Close()
    Return TempString
End Function

The 2nd part (I test it many times, the search and replace does not work. I checked many times that the "TempText" DOES contain string. The "the_key_string" DOES inside the "TempText" String. I check it by using QuickWatch in VB.net. However, the replace function does NOT do its job)

            Dim TextPath = C:xxxxxx
            TempText = ReadTextFile(TextPath)
            TempText.Replace("the_key_string", "replace_by_this_string")

Please help. I have no clue where I made the mistake

like image 576
Marco Avatar asked Oct 07 '13 20:10

Marco


2 Answers

String.Replace returns new string instead of modifying the source one. You have to assign it back to your variable:

TempText = TempText.Replace("the_key_string", "replace_by_this_string")

From MSDN:

Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

like image 200
MarcinJuraszek Avatar answered Nov 10 '22 02:11

MarcinJuraszek


Strings are immutable, that means once they are created you cannot modify them. So you have to create a new one and assign that to your string variable:

TempText = TempText.Replace("the_key_string", "replace_by_this_string")

MSDN: String Data Type (Visual Basic):

Once you assign a string to a String variable, that string is immutable, which means you cannot change its length or contents. When you alter a string in any way, Visual Basic creates a new string and abandons the previous one. The String variable then points to the new string.

like image 35
Tim Schmelter Avatar answered Nov 10 '22 02:11

Tim Schmelter