如何进行字符串插值?

115

我想在C#中实现以下内容(来自Python背景):

strVar = "stack"
mystr  = "This is %soverflow" % (strVar)

如何将字符串中的令牌替换为其外部的值?

16个回答

0
你可以使用以下方式:

字符串插值

字符$将一个字符串文字标识为插值字符串。例如:

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

0

使用 string.Replace 实现占位符的另一种方法,在某些情况下非常奇妙:

mystr = mystr.Replace("%soverflow", strVar);

0

C#具有内置的插值机制,完全没有必要为此功能包含库。 - Display name
3
请看问题中的日期。C#并没有一开始就内置字符串插值。它是在2016年的C# 6中添加的。因此,这就是我在2014年回答的原因。 - anderly

0

-1
你可以使用美元符号和花括号。
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");

请查看文档这里


-1

基本示例:

        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#中的字符串插值示例


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接