将值从变量替换为另一个值

时间:2013-11-21 16:27:07

标签: c# .net string

我有一个控制器,我将html文件读入变量。

读完之后,我将变量中的一些值替换为其他值,

但问题是没有任何事情发生。

这里有什么问题?

有人能帮我一把吗?

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");

2 个答案:

答案 0 :(得分:4)

字符串是不可变的 - 您应该将替换结果分配给您的字符串。您也可以链接替换操作:

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

请记住 - 所有字符串操作(如Replace,Substring等)都将创建并返回新字符串,而不是更改原始字符串。同样意味着对DateTime和其他不可变对象的操作。

更新:您还可以声明替换字典并在循环中更新字符串:

 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);

答案 1 :(得分:2)

字符串是不可变的。基本上,如果一个对象创建后状态不会改变,则该对象是不可变的。因此,如果一个类的实例是不可变的,那么它是不可变的。

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");
相关问题