简体   繁体   English

C# .NET 中的 String.Replace

[英]String.Replace in C# .NET

I would like to know why it is not working:我想知道为什么它不起作用:

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

I don't have any error, but my string doesn't change.我没有任何错误,但我的字符串没有改变。

There may be other problems as well, but what jumped out at me right away is that the Replace() function does not change the string .可能还有其他问题,但让我立即想到的是Replace()函数不会更改 string Instead, it returns a new string.相反,它返回一个新字符串。 Therefore, you need to assign the result of the function back to the original:因此,您需要将函数的结果赋值回原来的:

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

The String.Replace method returns a new string. String.Replace方法返回一个新字符串。 It doesn't change the original string.它不会改变原始字符串。

Returns a new string in which all occurrences of a specified Unicode character or String in the current string are replaced with another specified Unicode character or String返回一个新字符串,其中当前字符串中所有出现的指定 Unicode 字符或字符串都被另一个指定的 Unicode 字符或字符串替换

So, you should assign a new string or an existing one inside your foreach loop:因此,您应该在foreach循环中分配一个新字符串或现有字符串:

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

or要么

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

And remember, in .NET, strings are immutable types .请记住,在 .NET 中,字符串是不可变类型 You can't change them.你不能改变它们。 Even if you think you change them, you create new string objects.即使您认为您更改了它们,您也会创建新的字符串对象。

In

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

just do the below change:只需进行以下更改:

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

This is the completed code:这是完成的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM