如何避免C#替换以通过第二次替换再次替换新字符串

Omt*_*guy 1 c# replace

假设我想将"First Name"和"Name"这两个短语替换为"#First Name".

例如:

string text = "first name and name should be with # as preffix and suffix";
text = text.Replace("first name", "#first name#");
text = text.Replace("name", "#name#");
Console.WriteLine(text);
Run Code Online (Sandbox Code Playgroud)

我希望输出结果为:"#first name#和#name#应该用#作为预加词和后缀"

但是第二个替换也替换了被替换的文本,因此短语#first name#中的"名称"再次被替换:#first#name ##和#name#应该用#作为预加词和后缀.

是否可以选择保护以#开头和结尾的短语,或者对两个短语进行"一次拍摄"替换?

谢谢.

第一次更换后:"我的全名是我的#first name#和我的姓氏在一起"

Igo*_*evo 6

使用中间值:

string text = "first name and name should be with # as preffix and suffix";
text = text.Replace("first name", "#SOME_UNIQUE_CODE#");
text = text.Replace("name", "#name#");
text = text.Replace("#SOME_UNIQUE_CODE#", "#first name#");
Console.WriteLine(text);
Run Code Online (Sandbox Code Playgroud)

或者使用正则表达式替换.