Best way to replace tokens in a large text template

后端 未结 10 1752
我在风中等你
我在风中等你 2020-12-08 17:14

I have a large text template which needs tokenized sections replaced by other text. The tokens look something like this: ##USERNAME##. My first instinct is just to use Stri

10条回答
  •  不思量自难忘°
    2020-12-08 17:45

    If your template is large and you have lots of tokens, you probably don't want walk it and replace the token in the template one by one as that would result in an O(N * M) operation where N is the size of the template and M is the number of tokens to replace.

    The following method accepts a template and a dictionary of the keys value pairs you wish to replace. By initializing the StringBuilder to slightly larger than the size of the template, it should result in an O(N) operation (i.e. it shouldn't have to grow itself log N times).

    Finally, you can move the building of the tokens into a Singleton as it only needs to be generated once.

    static string SimpleTemplate(string template, Dictionary replacements)
    {
       // parse the message into an array of tokens
       Regex regex = new Regex("(##[^#]+##)");
       string[] tokens = regex.Split(template);
    
       // the new message from the tokens
       var sb = new StringBuilder((int)((double)template.Length * 1.1));
       foreach (string token in tokens)
          sb.Append(replacements.ContainsKey(token) ? replacements[token] : token);
    
       return sb.ToString();
    }
    

提交回复
热议问题