String.Replace C#.NET

时间:2013-09-02 14:37:56

标签: c# .net replace

我想知道它为什么不起作用

string filename = optionFileNameFormat; // "{year}-{month}-{day} {name}"
Dictionary<string, string> tagList = new Dictionary<string, string>();
tagList.Add("author",System.Security.Principal.WindowsIdentity.GetCurrent().Name);
tagList.Add("year" , "" + DateTime.Now.Year);
tagList.Add("month", "" + DateTime.Now.Month);
tagList.Add("day"  , "" + DateTime.Now.Day);

foreach (var property in tagList)
{
    filename.Replace(@"{" + property.Key + @"}", property.Value);
}

我没有任何错误,但我的字符串没有改变。 感谢

4 个答案:

答案 0 :(得分:12)

也可能存在其他问题,但是立即跳出来的是Replace()函数不会更改字符串。相反,它返回一个新字符串。因此,您需要将函数的结果分配回原始:

filename = filename.Replace(@"{" + property.Key + @"}", property.Value);

答案 1 :(得分:3)

String.Replace方法返回新字符串。它不会更改原始字符串。

  

返回一个新字符串,其中所有出现的指定Unicode   当前字符串中的字符或字符串将替换为另一个字符串   指定的Unicode字符或字符串

因此,您应该在foreach循环内部分配一个新字符串或现有字符串。

filename = filename.Replace(@"{" + property.Key + @"}", property.Value);

string newfilename = filename.Replace(@"{" + property.Key + @"}", property.Value);

请记住,在.NET中,字符串是 immutable types 。你无法改变它们。即使您认为自己更改了它们,也可以创建新的字符串对象。

答案 2 :(得分:1)

foreach (var property in tagList)
{
    filename.Replace(@"{" + property.Key + @"}", property.Value);
}

只需进行以下更改:

filename =  filename.Replace(@"{" + property.Key + @"}", property.Value);

答案 3 :(得分:1)

这是完成的代码

 string filename = optionFileNameFormat; // "{year}-{month}-{day} {name}"
 Dictionary<string, string> tagList = new Dictionary<string, string>();
 tagList.Add("author",System.Security.Principal.WindowsIdentity.GetCurrent().Name);
 tagList.Add("year" , "" + DateTime.Now.Year);
 tagList.Add("month", "" + DateTime.Now.Month);
 tagList.Add("day"  , "" + DateTime.Now.Day);

 foreach (var property in tagList)
 {
  filename= filename.Replace(@"{" + property.Key + @"}", property.Value);
 }