Jim
Jim

Reputation: 801

How do I create a string intermixed with specially formatted placeholders for custom text

I would like to create a string which has a placeholder held within curly brackets for custom text. For example

string mySpecialMessage = "Hi there developer {name}. 
I see that you have {reputation} reputation points! 
Thanks for looking at my stack overflow. You're a real {compliment}";

I would then feed it into a method

Display(mySpecialMessage, MessageType.HighPriority, 2);

And the method looks like this

public void Display (string messageContents, messageType messageType, float displayDuration)
{
// TODO - Format messageContents with replaced placeholders
// Create a new instance of message

Message newMessage = new Message(messageContents, messageType, displayDuration);

// Adds message to queue

messageQueue.Enqueue(newMessage);
if (!processing)
    {
        StartCoroutine(ProcessMessageQueue());
    }
}
}

My question is: How do I extract all these curly brackets and format it back into the string?

Upvotes: 1

Views: 70

Answers (3)

String.Format() can also be used here:

Decimal pricePerOunce = 17.36m;
String s = String.Format("The current price is {0} per ounce.", pricePerOunce);
// Result: The current price is 17.36 per ounce.

The bracketed value {0} is replaced with the object (in the example, a float) passed as the next parameter. String.Format accepts multiple objects at once as well.

Although I like ceferrari's solution much better, as it can use named variables.

Upvotes: 0

ceferrari
ceferrari

Reputation: 1677

Use string interpolation:

string name = "Example Name";
string reputation = "Example Reputation";
string compliment = "Example Compliment";

string mySpecialMessage = 
    $"Hi there developer {name}. " +
    $"I see that you have {reputation} reputation points!" +
    $"Thanks for looking at my stack overflow.You're a real {compliment}";

Note the $ before the string.

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values. It is a form of simple template processing or, in formal terms, a form of quasi-quotation (or logic substitution interpretation). String interpolation allows easier and more intuitive string formatting and content-specification compared with string concatenation.

Source

Upvotes: 2

Sandro Figo
Sandro Figo

Reputation: 183

mySpecialMessage.Replace("{name}", "Your Name");
mySpecialMessage.Replace("{reputation}", "123");
mySpecialMessage.Replace("{compliment}", "hero");

Upvotes: 0

Related Questions