Android Question Replacing a string in a text file

apty

Active Member
Licensed User
Longtime 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
B4X:
mynewfile=File.ReadString(File.DirDefaultExternal&"/testr/","Mai.txt")
    mynewfile = mynewfile.Replace ("kliev", "jared")
    File.WriteString(File.DirDefaultExternal&"/testr/","Mai.txt",mynewfile)
 

klaus

Expert
Licensed User
Longtime 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.
 
Upvote 0

ajk

Active Member
Licensed User
Longtime User
I have the same problem

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

and we habe Et3= "aaa DO bbb"

It seems to be .replace problem.
 
Upvote 0

Troberg

Well-Known Member
Licensed User
Longtime 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.
 
Upvote 0
Top