Replacing bad characters of a String with bad characters

前端 未结 6 1392
走了就别回头了
走了就别回头了 2020-12-11 17:12

I just wondered what\'s the easiest way to replace a string characters that must be replaced subsequently.

For example:

var str = \"[Hello World]\";         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-11 17:42

    I had the exact same problem, so I made a helper function to do just that

        protected string ReplaceUsingDictionary(string subject, Dictionary pairs)
        {
            StringBuilder sb = new StringBuilder(subject);
    
            sb.Replace("{", "{{").Replace("}", "}}");
    
            int i=0;
            foreach (string key in pairs.Keys.ToArray())
            {
                sb.Replace(
                    key.Replace("{", "{{").Replace("}", "}}"), 
                    "{" + i + "}"
                );
    
                i++;
            }
    
            return string.Format(sb.ToString(), pairs.Values.ToArray());
        }
    
    // usage
    Dictionary replacements = new Dictionary();
    replacements["["] = "[[]";
    replacements["]"] = "[]]";
    
    string mystr = ReplaceWithDictionary("[HelloWorld]", replacements); // returns [[]HelloWorld[]]
    

提交回复
热议问题