A simple string token replacement method in C#.
/// <summary>
/// Simple token replacement.
/// </summary>
/// <param name="tokens">
/// The replacement token dictionary. Note that token names are case-sensitive.
/// </param>
/// <param name="content">
/// The content that will be searched and replaced with an appropriate matching token.
/// </param>
/// <returns>A string with matched token keys replaced.</returns>
/// <example>
/// var replacementTokens = new Dictionary<string, string>
/// {
/// { "{Name}", "Jon" },
/// { "{Fax}", "(999) 999-9999" },
/// { "{Phone}", "(888) 888-8888" }
/// };
/// </example>
public static string ReplaceTokens(Dictionary<string, string> tokens, string content)
{
foreach (var token in tokens.Keys)
{
content = content.Replace(token, tokens[token]);
}
return content;
}
//
// Example Usage:
var replacementTokens = new Dictionary<string, string>
{
{ "{Name}", "Jon" },
{ "{Place}", "Some Place" }
};
var content = @"Thank you {Name} for scheduling at {Place}.";
var result = ReplaceTokens(replacementTokens, content);
Console.Write(result);