user2232273
user2232273

Reputation: 4974

Replace value from a variable to another value

i have a controller where i read a html file into a variable.

After read it i replace some values from the variable to other values,

but the problem is that nothing happend.

What is wrong here ?

can someone give me a hand with this?

string path = "/mypath/myfile.html";
string s = System.IO.File.ReadAllText(path);
s.Replace("@%a%@","hi");
s.Replace("@%b%@","yo");
s.Replace("@%c%@","asdfasdf");
s.Replace("@%d%@", "http://www.google.com");

Upvotes: 1

Views: 478

Answers (2)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236308

Strings are immutable - you should assign result of replacement to your string. Also you can chain replacement operations like this:

string s = System.IO.File.ReadAllText(path)
             .Replace("@%a%@","hi")
             .Replace("@%b%@","yo")
             .Replace("@%c%@","asdfasdf")
             .Replace("@%d%@", "http://www.google.com");

Just keep in mind - all string operations (like Replace, Substring etc) will create and return new string, instead of changing original. Same implies to operations on DateTime and other immutable objects.

UPDATE: You can also declare dictionary of your replacements and update string in a loop:

 var replacements = new Dictionary<string, string> {
     { "@%a%@","hi" }, { "@%b%@","yo" }, { "@%c%@","asdfasdf" } // ...
 };

 string s = System.IO.File.ReadAllText(path);

 foreach(var replacement in replacements)
    s = s.Replace(replacement.Key, repalcement.Value);

Upvotes: 4

crthompson
crthompson

Reputation: 15875

A string is immutable. Basically, an object is immutable if its state doesn’t change once the object has been created. Consequently, a class is immutable if its instances are immutable.

string path = "/mypath/myfile.html";
string s = System.IO.File.ReadAllText(path);
s = s.Replace("@%a%@","hi");
s = s.Replace("@%b%@","yo");
s = s.Replace("@%c%@","asdfasdf");
s = s.Replace("@%d%@", "http://www.google.com");

Upvotes: 2

Related Questions