如何创建与自定义文本

时间:2017-11-17 17:39:17

标签: c# string unity3d

我想创建一个字符串,其中占位符位于大括号内,用于自定义文本。例如

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}";

然后我会将它提供给方法

Display(mySpecialMessage, MessageType.HighPriority, 2);

方法看起来像这样

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());
    }
}
}

我的问题是:如何提取所有这些大括号并将其格式化回字符串?

3 个答案:

答案 0 :(得分:2)

使用字符串插值:

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}";

请注意字符串前的$

  

在计算机编程中,字符串插值(或变量插值,变量替换或变量扩展)是评估包含一个或多个占位符的字符串文字的过程,从而产生一个结果,其中占位符将替换为其对应的值。它是一种简单的模板处理形式,或者在形式上,是一种准引用(或逻辑替换解释)的形式。与字符串连接相比,字符串插值允许更简单,更直观的字符串格式化和内容规范。

Source

答案 1 :(得分:0)

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

答案 2 :(得分:0)

String.Format()也可以在这里使用:

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.

括号中的值{0}将替换为作为下一个参数传递的对象(在示例中为浮点数)。 String.Format同时接受多个对象。

虽然我更喜欢ceferrari的解决方案,因为它可以使用命名变量。

相关问题