How to provide custom string placeholder for string format

56,312

Solution 1

You might want to check out FormatWith 2.0 by James Newton-King. It allows you to use property names as formatting tokens such as this:

var user = new User()
{
    Name = "Olle Wobbla",
    Age = 25
};

Console.WriteLine("Your name is {Name} and your age is {Age}".FormatWith(user));

You can also use it with anonymous types.

UPDATE: There is also a similar solution by Scott Hanselman but it is implemented as a set of extension methods on Object instead of String.

UPDATE 2012: You can get Calrius Consulting's NETFx String.FormatWith Extension Method NuGet package on NuGet.org

UPDATE 2014: There is also StringFormat.NET and littlebit's StringFormat

Solution 2

Regex with a MatchEvaluator seems a good option:

static readonly Regex re = new Regex(@"\{([^\}]+)\}", RegexOptions.Compiled);
static void Main()
{
    string input = "this {foo} is now {bar}.";
    StringDictionary fields = new StringDictionary();
    fields.Add("foo", "code");
    fields.Add("bar", "working");

    string output = re.Replace(input, delegate (Match match) {
        return fields[match.Groups[1].Value];
    });
    Console.WriteLine(output); // "this code is now working."
}

Solution 3

I saw all the answers above, yet, couldn't get the question right :)

Is there any particular reason why the following code does not meet your requirement?

string myFirstStr = GetMyFirstStrFromSomewhere();
string mySecondStr = GetMySecondStrFromSomewhere();

string result = "Enter " + myFirstStr + " " + mySecondStr + " name";

Solution 4

object[] myInts = new int[] {8,9}; 

However you can get away with:

object[] myInts = new string[] { "8", "9" }; 
string bar = string.Format("{0} {1}", myInts); 

Solution 5

You can also use the example from Marc Gravell and Extend the String class object:

public static class StringExtension
{
    static readonly Regex re = new Regex(@"\{([^\}]+)\}", RegexOptions.Compiled);
    public static string FormatPlaceholder(this string str, Dictionary<string, string> fields)
    {
        if (fields == null)
            return str;

        return re.Replace(str, delegate(Match match)
        {
            return fields[match.Groups[1].Value];
        });

    }
}

Example usage:

String str = "I bought a {color} car";
Dictionary<string, string> fields = new Dictionary<string, string>();
fields.Add("color", "blue");

str.FormatPlaceholder(fields));
Share:
56,312
Admin
Author by

Admin

Updated on March 29, 2020

Comments

  • Admin
    Admin about 4 years

    I have a string

    string str ="Enter {0} patient name";
    

    I am using string.format to format it.

    String.Format(str, "Hello");
    

    Now if i want patient also to be retrieved from some config then I need to change str to something like "Enter {0} {1} name". So it will replace the {1} with second value. The problem is that I want instead of {1} some other format something like {pat}. But when I try to use, it throws an error. The reason I want a different format is that there are lot of files I need to change like this(which may contain {0},{1} etc). So I need a custom placeholder which can be replaced at run-time.