Search code examples
c#string-interpolation

String interpolation by user input


is possible to make interpolation based on user input?

For example something like this:

public string Foo(string input)
{
    string user = "random_user_name";
    string address = "random_address";
    string city = "random_city";

    return $"{input}";
}
  • Example input1: "{user}, {city}"
  • Expected output1: "random_user_name, random_city"
  • Example input2: "{address}"
  • Expected output2: "random_address"
  • Example input3: "{city}, {address}"
  • Expected output3: "random_city, random_address"

I need that user can define which variables want and their order. Btw user will know variable names.


Solution

  • Taking @TheGeneral's suggestion, I did the following:

    The first thing I did was to change your three strings into a Dictionary<string, string>

    var tokens = new Dictionary<string, string> {
        { "user", "random_user_name" },
        { "address", "random_address" },
        { "city",  "random_city" }
    };
    

    Then I created a worker function that does the replacement in the way @TheGeneral described

    public static string DoReplacement(string key, Dictionary<string, string> tokens)
    {
        var result = new StringBuilder(key);
        foreach (var kvp in tokens)
        {
            result.Replace("{" + kvp.Key + "}", kvp.Value);
        }
        return result.ToString();
    }
    

    And finally, I wrapped it all together:

    public static string Test(string input)
    {
        var tokens = new Dictionary<string, string> {
            { "user", "random_user_name" },
            { "address", "random_address" },
            { "city",  "random_city" }
        };
    
        return $"{DoReplacement(input, tokens)}";
    }
    

    To exercise this, I called it with the OP's examples:

    var tests = new List<string> {
        "{user}, {city}",
        "{address}",
        "{city}, {address}",
    };
    foreach (var s in tests)
    {
        var replaced = StringReplacement.Test(s);
        Debug.WriteLine(replaced);
    }
    

    and got this output:

    random_user_name, random_city
    random_address
    random_city, random_address