C# String Token Replacer

Imagine this classic text where you need to replace tokens with some values:

Welcome {{user}}. Click on this link to confirm your subscription: {{url}}.

Tokens encapsulated in double brackets {{token}} are commonly used to mark tokens to be replaced with real values.

It’s simple to make your own token replacer:

using System.Collections.Generic;

namespace MyCode
{
  public static class TokenReplacer
  {
    public static string ReplaceTokens(this string s, Dictionary<string, string> tokens)
    {
      if (tokens == null)
        return s;

      foreach (var token in tokens)
        s = s.Replace("{{" + token.Key + "}}", token.Value);

      return s;
    }
  }
}

Usage is easy:

var tokenValues = new System.Collections.Generic.Dictionary<string, string>();
tokenValues.Add("user", "briancaos");
tokenValues.Add("url", "https://briancaos.wordpress.com/");
string text = "Welcome {{user}}. Click on this link to confirm your subscription: {{url}}.";
Console.WriteLine(text.ReplaceTokens(tokenValues));

// Output is:
// Welcome briancaos. Click on this link to confirm your subscription: https://briancaos.wordpress.com/.

That’s it. Happy coding.

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, c#, General .NET and tagged , , , , . Bookmark the permalink.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.