Stringy is a simple and light-weight runtime string interpolation engine. Built as a utility for a text-based game, the purpose of the library is to provide something that's easier to use and more light-weight than Runtime Text Templates or RazorEngine, but a little more powerful than string.Replace()
.
On top of string interpolation, Stringy can also be used to facilitate simple expression evaluation. For example, suppose you want to store an arbitrary conditional statement as a "saved filter" for some list of items. You could write your filtering code like so:
string filterStr = "person.Age < 18 && person.Firstname.StartsWith('A')"; // Fetch from database
IStringy engine = new Stringy();
// Assume "people" is an IEnumerable of Person objects
var people = GetListOfPersonObjects();
var filteredPeople = people.Where(p => engine.Set("person", p).EvaluateExpression<bool>(filterStr));
// filteredPeople contains only those Persons with a first name
// that starts with the letter A, and an age lower than 18
Stringy favours light string replacement and basic logic and branching needs. If you want to produce large bodies of (formatted) text using complex logic, you will probably find it worth it to use a full templating solution like RazorEngine. Use Stringy if:
-
Your string templates require basic logic and branching but you don't need the full power of C#.
-
You keep strings in a database/persistent storage and your substitution needs are greater than what can be achieved with regular expressions and
string.Replace()
. -
You need to execute methods and access properties on your model objects from inside your string templates.
-
You need to evaluate stored/persisted expressions
Simply add the Stringy NuGet package to your solution:
dotnet add package Stringy
dotnet restore
Or, using powershell:
Install-Package Stringy
string str = "Hello World";
const string template = "Substitute this: {value}";
IStringy engine = new Stringy();
engine.Set("value", str);
// Prints: Substitute this: Hello World
Console.WriteLine(engine.Execute(template));
Using engine.Set()
you can add any object and its methods and properties will be available in your string templates.
int num1 = 6;
int num2 = 7;
const string template = "{a} * {b} = {a * b}";
IStringy engine = new Stringy();
engine.Set("a", num1);
engine.Set("b", num2);
// Prints: 6 * 7 = 42
Console.WriteLine(engine.Execute(template));
string str = "Hello World";
const string template = "The lowercase string '{value.ToLower()}' has {value.Length} characters";
IStringy engine = new Stringy();
engine.Set("value", str);
// Prints: The lowercase string 'hello world' has 11 characters
Console.WriteLine(engine.Execute(template));
bool userIsFemale = true;
const string template = "Welcome, dear {isFemale ? 'Lady' : 'Sir'}";
IStringy engine = new Stringy();
engine.Set("isFemale", userIsFemale);
// Prints: Welcome, dear Lady
Console.WriteLine(engine.Execute(template));
Apache 2.0