Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# String replace with dictionary

I have a string on which I need to do some replacements. I have a Dictionary<string, string> where I have search-replace pairs defined. I have created following extension methods to perform this operation:

public static string Replace(this string str, Dictionary<string, string> dict) {     StringBuilder sb = new StringBuilder(str);      return sb.Replace(dict).ToString(); }  public static StringBuild Replace(this StringBuilder sb,      Dictionary<string, string> dict) {     foreach (KeyValuePair<string, string> replacement in dict)     {         sb.Replace(replacement.Key, replacement.Value);     }      return sb; } 

Is there a better way of doing that?

like image 780
RaYell Avatar asked Aug 05 '09 07:08

RaYell


2 Answers

If the data is tokenized (i.e. "Dear $name$, as of $date$ your balance is $amount$"), then a Regex can be useful:

static readonly Regex re = new Regex(@"\$(\w+)\$", RegexOptions.Compiled); static void Main() {     string input = @"Dear $name$, as of $date$ your balance is $amount$";      var args = new Dictionary<string, string>(         StringComparer.OrdinalIgnoreCase) {             {"name", "Mr Smith"},             {"date", "05 Aug 2009"},             {"amount", "GBP200"}         };     string output = re.Replace(input, match => args[match.Groups[1].Value]); } 

However, without something like this, I expect that your Replace loop is probably about as much as you can do, without going to extreme lengths. If it isn't tokenized, perhaps profile it; is the Replace actually a problem?

like image 111
Marc Gravell Avatar answered Sep 19 '22 22:09

Marc Gravell


Do this with Linq:

var newstr = dict.Aggregate(str, (current, value) =>       current.Replace(value.Key, value.Value)); 

dict is your search-replace pairs defined Dictionary object.

str is your string which you need to do some replacements with.

like image 33
Allen Wang Avatar answered Sep 19 '22 22:09

Allen Wang