How do I interpolate strings?

前端 未结 15 703
感情败类
感情败类 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();
    
    0 讨论(0)
  • 2020-11-27 05:49

    Use string.Format:

    string mystr = string.Format("This is {0}overflow", "stack");
    
    0 讨论(0)
  • 2020-11-27 05:49

    You can use the dollar sign and curl brackets.

    Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
    

    See doc here.

    0 讨论(0)
  • 2020-11-27 05:52

    You have 2 options. You can either use String.Format or you can use the concatenation operator.

    String newString = String.Format("I inserted this string {0} into this one", oldstring);
    

    OR

    String newString = "I inserted this string " + oldstring + " into this one";
    
    0 讨论(0)
  • 2020-11-27 05:52

    You can use the following way

    String interpolation

    The $ special character identifies a string literal as an interpolated string. e.g.

    string name = "Mark";
    string surname = "D'souza";
    WriteLine($"Name :{name} Surname :{surname}" );//Name :Mark Surname :D'souza  
    

    An interpolated string is a string literal that might contain interpolated expressions. When an interpolated string is resolved to a result string, items with interpolated expressions are replaced by the string representations of the expression results.

    String.Format

    Use String.Format if you need to insert the value of an object, variable, or expression into another string.E.g.

    WriteLine(String.Format("Name: {0}, Surname : {1}", name, surname));
    
    0 讨论(0)
  • 2020-11-27 05:53

    C# 6.0

    string mystr = $"This is {strVar}overflow";
    
    0 讨论(0)
提交回复
热议问题