How do I interpolate strings?

前端 未结 15 705
感情败类
感情败类 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:55

    This has been added as of C# 6.0 (Visual Studio 2015+).

    Example:

    var planetName = "Bob";
    var myName = "Ford"; 
    var formattedStr = $"Hello planet {planetName}, my name is {myName}!";
    // formattedStr should be "Hello planet Bob, my name is Ford!"
    

    This is syntactic sugar for:

    var formattedStr = String.Format("Hello planet {0}, my name is {1}!", planetName, myName);
    

    Additional Resources:

    String Interpolation for C# (v2) Discussion

    C# 6.0 Language Preview

    0 讨论(0)
  • 2020-11-27 06:03

    Basic example:

            var name = "Vikas";
            Console.WriteLine($"My name is {name}");
    

    Adding Special characters:

    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 :-{
    

    Not just replacing token with value, You can do a lot more with string interpolation in C#

    Evaluating Expression

    Console.WriteLine($"The greater one is: { Math.Max(10, 20) }");
    //output - The greater one is: 20
    

    Method call

        static void Main(string[] args)
        {
            Console.WriteLine($"The 5*5  is {MultipleByItSelf(5)}");
        }
      
        static int MultipleByItSelf(int num)
        {           
            return num * num;
        }
    

    Source: String Interpolation in C# with examples

    0 讨论(0)
  • 2020-11-27 06:07

    You can accomplish this with Expansive: https://github.com/anderly/Expansive

    0 讨论(0)
  • 2020-11-27 06:08

    There's one more way to implement placeholders with string.Replace, oddly helps in certain situations:

    mystr = mystr.Replace("%soverflow", strVar);
    
    0 讨论(0)
  • 2020-11-27 06:09

    If you currently use Visual Studio 2015 with C# 6.0, try the following:

    var strVar = "stack";
    
    string str = $"This is {strVar} OverFlow";
    

    that feature is called string interpolation.

    0 讨论(0)
  • 2020-11-27 06:11

    There is no operator for that. You need to use string.Format.

    string strVar = "stack";
    string mystr  = string.Format("This is {0}soverflow", strVar);
    

    Unfortunately string.Format is a static method, so you can't simply write "This is {0}soverflow".Format(strVar). Some people have defined an extension method, that allows this syntax.

    0 讨论(0)
提交回复
热议问题