views:

1346

answers:

5

Hi, I have a string

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

So I am using using string.format to format that.

String.Format(str, "Hello");

Now if i want patient also to be retireved from some config then i need to change str something like "Enter {0} {1} name". So it will replace the {1} with second value. the problem for me is that i want instead of {1} some toher format something like {pat}. But when i try to use it throws an error. The reason i want a diff format is that there r lot of files I need to change like this(which may contian {0},{1} etc). So I need a custom placeholder which can be replaced @ runtime.

A: 

Use string replacement:

    string test = "{one} {two}";
    test = test.Replace("{one}", "ONE");
    test = test.Replace("{one}", "TWO");
Martin Buberl
I found this method very useful when using placeholders in a javascript text with many curly brackets.
mathijsuitmegen
+2  A: 

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."
}
Marc Gravell
+6  A: 

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.

Manga Lee
+1. That's interesting, I've not seen that before. Looks like it works well with anonymous types.
RichardOD
A: 

You are probably better off using Replace for the custom field and Format for the rest, like:

string str = "Enter {0} {pat} name";
String.Format(str.Replace("{pat}", "Patient"), "Hello");
Dean Povey
A: 

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";
Chansik Im