C# String replace with dictionary

前端 未结 8 2279
谎友^
谎友^ 2020-11-29 02:07

I have a string on which I need to do some replacements. I have a Dictionary where I have search-replace pairs defined. I have created fol

8条回答
  •  一向
    一向 (楼主)
    2020-11-29 03:04

    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(
            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?

提交回复
热议问题