fastest way to replace string in a template

2020-02-21 08:31发布

I have some template string

this is my {0} template {1} string

which I plan to put user values in using String.Format().

The string actually is longer so for readability I use:

this is my {goodName1} template {goodName2} string

And then String.Replace each parameter with its value.

How can I get the highest performance and readability?

Maybe I should not have this template in a file (as now) but dynamically build it by concatanating to a string builder and adding the params when required? Although it's less readable.

What's my other options?

9条回答
该账号已被封号
2楼-- · 2020-02-21 08:52
够拽才男人
3楼-- · 2020-02-21 08:52

The same thing above that Fredrick posted above, but with linq.

    public static string FindandReplace(this string inputText, Dictionary<string, string> placeHolderValues)
    {
        if (!string.IsNullOrEmpty(inputText))
        {
            return placeHolderValues.Keys.Aggregate(inputText, (current, key) => current.Replace(key, placeHolderValues[key]));
        }
        else return inputText;
    }
查看更多
时光不老,我们不散
4楼-- · 2020-02-21 09:01

If you need a good, fast, but simple template engine, you should check out StringTemplate. For simple templates that don't require any logic or flow control in the template itself, StringTemplate is GREAT.

http://www.stringtemplate.org/download.html

查看更多
登录 后发表回答