user3014254
user3014254

Reputation: 27

Importing String with variables from Txt file

I need to import text from txt file with some variables. I use BufferedReader and File Reader. In code I have :

String car = "vw golf";
String color = "nice sunny blue color";

And in my txt file:

I have nice " +car+ " which has "+color+".

My expected output :

I have nice vw golf which has nice sunny blue color.

My actual output is :

I have nice " +car+ " which has "+color+".

Upvotes: 1

Views: 54

Answers (1)

Kate
Kate

Reputation: 1576

If I've understood correctly, what you want to do is replace " + car + " with the value of your car string and likewise for colour. You've tried to do this by writing your text file as if it were a command to be evaluated. However, that won't happen - it will just be outputted as is. I'm going to assume you are using c#. What you need to do is, prior to outputting your string, parse it to replace the markers with the variables. I would recommend you get rid of the double quotes in your text file. You could then do something like this:

string text = this.ReadTextFromFile();
string ammended = text.Replace("+car+", car);

As mentioned, this is assuming you remove the double quotes from your text file so it reads:

I have nice +car+ which has +color+.

Also, you don't need to use the + symbols, but I suppose they are a good way of designating a unique token to be replaced. You could use {car} in the file and then likewise in the Replace startment, for example.

I may not have properly understood what you wanted to do, of course!

Edit: Incase of confustion,

this.ReadTextFile();

was just a short hand way of saying that the text variable contains the contents as read from your text file.

Upvotes: 1

Related Questions