How do I interpolate strings?

前端 未结 15 773
感情败类
感情败类 2020-11-27 05:38

I want to do the following in C# (coming from a Python background):

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

How do I

15条回答
  •  抹茶落季
    2020-11-27 05:49

    You can use string.Format to drop values into strings:

    private static readonly string formatString = "This is {0}overflow";
    ...
    var strVar = "stack";
    var myStr = string.Format(formatString, "stack");
    

    An alternative is to use the C# concatenation operator:

    var strVar = "stack";
    var myStr = "This is " + strVar + "overflow";
    

    If you're doing a lot of concatenations use the StringBuilder class which is more efficient:

    var strVar = "stack";
    var stringBuilder = new StringBuilder("This is ");
    for (;;)
    {
        stringBuilder.Append(strVar); // spot the deliberate mistake ;-)
    }
    stringBuilder.Append("overflow");
    var myStr = stringBuilder.ToString();
    

提交回复
热议问题