How do I interpolate strings?

C#StringString Interpolation

C# Problem Overview


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

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

How do I replace the token inside the string with the value outside of it?

C# Solutions


Solution 1 - C#

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][1]

[C# 6.0 Language Preview][2]

[1]: https://roslyn.codeplex.com/discussions/570614 "String Interpolation for C# (v2) Discussion" [2]: http://msdn.microsoft.com/en-us/magazine/dn802602.aspx "C# 6.0 Language Preview "

Solution 2 - C#

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

And you could also use named parameters instead of indexes.

Solution 3 - C#

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

Solution 4 - C#

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.

Solution 5 - C#

C# 6.0

string mystr = $"This is {strVar}overflow";

Solution 6 - C#

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.

Solution 7 - C#

Use string.Format:

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

Solution 8 - C#

You should be using String.Format(). The syntax is a bit different, numerical placeholders are used instead.

Example:

String.Format("item {0}, item {1}", "one", "two")

Have a look at http://msdn.microsoft.com/en-us/library/system.string.format.aspx for more details.

Solution 9 - C#

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

Solution 10 - C#

Use:

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

Solution 11 - C#

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

Solution 12 - C#

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

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

Solution 13 - C#

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

Solution 14 - C#

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

Solution 15 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsazrView Question on Stackoverflow
Solution 1 - C#AshtonianView Answer on Stackoverflow
Solution 2 - C#Darin DimitrovView Answer on Stackoverflow
Solution 3 - C#David ClarkeView Answer on Stackoverflow
Solution 4 - C#SakalView Answer on Stackoverflow
Solution 5 - C#Sylvain RodrigueView Answer on Stackoverflow
Solution 6 - C#CodesInChaosView Answer on Stackoverflow
Solution 7 - C#Matthew AbbottView Answer on Stackoverflow
Solution 8 - C#Bruno SilvaView Answer on Stackoverflow
Solution 9 - C#DwayneAllenView Answer on Stackoverflow
Solution 10 - C#Phillip NganView Answer on Stackoverflow
Solution 11 - C#anderlyView Answer on Stackoverflow
Solution 12 - C#Talha ImamView Answer on Stackoverflow
Solution 13 - C#SUNIL DHAPPADHULEView Answer on Stackoverflow
Solution 14 - C#Vikas LalwaniView Answer on Stackoverflow
Solution 15 - C#YgalbelView Answer on Stackoverflow