Replace multiple words in string

后端 未结 8 1129
独厮守ぢ
独厮守ぢ 2020-12-18 19:02

I have multiple words I want to replace with values, whats the best way to do this?

Example: This is what I have done but it feels and looks so wrong



        
8条回答
  •  太阳男子
    2020-12-18 19:24

    To build on George's answer, you could parse the message into tokens then build the message from the tokens.

    If the template string was much larger and there are more tokens, this would be a tad more efficient as you are not rebuilding the entire message for each token replacement. Also, the generation of the tokens could be moved out into a Singleton so it is only done once.

    // Define name/value pairs to be replaced.
    var replacements = new Dictionary();
    replacements.Add("", client.FullName);
    replacements.Add("", event.EventDate.ToString());
    
    string s = "Dear , your booking is confirmed for the ";
    
    // Parse the message into an array of tokens
    Regex regex = new Regex("(<[^>]+>)");
    string[] tokens = regex.Split(s);
    
    // Re-build the new message from the tokens
    var sb = new StringBuilder();
    foreach (string token in tokens)
       sb.Append(replacements.ContainsKey(token) ? replacements[token] : token);
    s = sb.ToString();
    

提交回复
热议问题