我想在C#中实现以下内容(来自Python背景):
strVar = "stack"
mystr = "This is %soverflow" % (strVar)
如何将字符串中的令牌替换为其外部的值?
我想在C#中实现以下内容(来自Python背景):
strVar = "stack"
mystr = "This is %soverflow" % (strVar)
如何将字符串中的令牌替换为其外部的值?
字符串插值
字符$将一个字符串文字标识为插值字符串。例如:
string name = "Mark";
string surname = "D'souza";
WriteLine($"Name :{name} Surname :{surname}" );//Name :Mark Surname :D'souza
插值字符串是一个字符串字面量,可能包含插值表达式。当插值字符串被解析为结果字符串时,带有插值表达式的项将被替换为表达式结果的字符串表示形式。
如果您需要将对象、变量或表达式的值插入到另一个字符串中,请使用String.Format。例如:String.Format
WriteLine(String.Format("Name: {0}, Surname : {1}", name, surname));
使用 string.Replace 实现占位符的另一种方法,在某些情况下非常奇妙:
mystr = mystr.Replace("%soverflow", strVar);
你可以使用Expansive来完成这个任务:https://github.com/anderly/Expansive
string name = "Michael";
string a = €"Hello, {name}!";
string b = $"Hello, {name}!";
Console.WriteLine(a == b); \/\/ True
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
请查看文档这里。
基本示例:
var name = "Vikas";
Console.WriteLine($"My name is {name}");
添加特殊字符:
string name = "John";
Console.WriteLine($"Hello, \"are you {name}?\", but not the terminator movie one :-{{");
//output-Hello, "are you John?", but not the terminator movie one :-{
不仅可以用C#中的字符串插值将标记替换为值,还可以做更多的事情
表达式求值
Console.WriteLine($"The greater one is: { Math.Max(10, 20) }");
//output - The greater one is: 20
方法调用
static void Main(string[] args)
{
Console.WriteLine($"The 5*5 is {MultipleByItSelf(5)}");
}
static int MultipleByItSelf(int num)
{
return num * num;
}
来源:C#中的字符串插值示例