Android Question Replacing a string in a text file

Discussion in 'Android Questions' started by apty, Feb 27, 2015.

  1. apty

    apty Active Member Licensed User

    I tried the code below to replace a specific string in a text file. I am not getting any error but the replacement is not working. Please advice what i am doing wrong
        mynewfile = mynewfile.Replace (
  2. klaus

    klaus Expert Licensed User

    What is not working ?

    Put a breakpoint in the second line.
    Check the content of mynewfile. Is the reading OK ?
    Go one step further and check mynewfile again. Did the content change ?
    Go one step further to save the file.
    Add a new line reading the file back and check.
  3. ajk

    ajk Active Member Licensed User

    I have the same problem

    Dim abc As String
    abc= "aaa DO bbb"
    abc.Replace("DO", "AAA")

    and we habe Et3= "aaa DO bbb"

    It seems to be .replace problem.
  4. klaus

    klaus Expert Licensed User

    This is wrong:
    abc.Replace("DO", "AAA")
    but this works:
    abc = abc.Replace("DO", "AAA")
    ajk, lemonisdead and Erel like this.
  5. Erel

    Erel Administrator Staff Member Licensed User

    This is a common mistake.

    Remember that strings are immutable (unlike StringBuilder).
    This means that the only way to change the string value referenced by abc is by assigning a new string to abc.
    valentino s likes this.
  6. Troberg

    Troberg Well-Known Member Licensed User

    Just to make it even clearer:

    This code is correct:

    abc = abc.Replace("DO", "AAA")

    It does the replace and returns it, and we place it in a variable (which happens to be the same variable we started with).

    This code is not correct:

    abc.Replace("DO", "AAA")

    It does the replace and returns it, but we do nothing with the return value, we just throw it away.

    A very easy mistake to make, even if one knows it's wrong. The brain is a bit lazy sometimes, and tends to forget such details. I've done it myself, several times.

    Perhaps an issue the compiler should raise a warning about? I can't see any reason under any circumstance to do it the wrong way, so a warning feels apropriate.
    DonManfred likes this.
  7. ajk

    ajk Active Member Licensed User

    Great thanks !
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice