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

后端 未结 6 511
生来不讨喜
生来不讨喜 2020-12-11 05:06

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

相关标签:
6条回答
  • 2020-12-11 05:18

    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.

    0 讨论(0)
  • 2020-12-11 05:23

    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.

    0 讨论(0)
  • 2020-12-11 05:24

    The Replace method returns the modified string.

    You need something like this:

    Dim TextPath = C:xxxxxx
    TempText = ReadTextFile(TextPath)
    Dim ModifiedString as String
    ModifiedString = TempText.Replace("the_key_string", "replace_by_this_string")
    
    0 讨论(0)
  • 2020-12-11 05:24

    "this is a string" If you do Replace 'string' with 'whatever' this string should be: "this is a whatever". so what you can do is put that in a new string. how? replace method returns a string so, it is easy :) see this: msdn

    0 讨论(0)
  • 2020-12-11 05:30

    You have to assign the value to something, like :

    TempText = TempText.Replace("the_key_string", "replace_by_this_string")
    
    0 讨论(0)
  • 2020-12-11 05:39

    This is performing the string replace, but it's not putting the result of it anywhere:

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

    You need to assign the result to something:

    TempText = TempText.Replace("the_key_string", "replace_by_this_string")
    
    0 讨论(0)
提交回复
热议问题