115

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?

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
sazr
  • 24,984
  • 66
  • 194
  • 362

16 Answers16

281

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

dtech
  • 13,741
  • 11
  • 48
  • 73
Ashtonian
  • 4,371
  • 2
  • 18
  • 25
  • Patch for mono (dated 2009, your mileage may vary) http://tirania.org/blog/archive/2009/Dec-20.html – Jefferey Cave Mar 18 '15 at 22:21
  • 1
    For the mono users: http://stackoverflow.com/questions/29208869/c-sharp-6-0-string-interpolation-in-mono-mcs – Jefferey Cave Jun 08 '15 at 22:27
  • This feature is such a beautiful thing. Especially with VS2015 and the editor support so you can clearly see the interpolated strings and get intellisense. It even works with methods! `$("This feature is {GetDescription(FEATURE_AMAZING))}");` – Patrick Aug 06 '16 at 02:03
85
string mystr = string.Format("This is {0}overflow", strVar);

And you could also use named parameters instead of indexes.

Csaba Toth
  • 10,021
  • 5
  • 75
  • 121
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
14

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();
David Clarke
  • 12,888
  • 9
  • 86
  • 116
12

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.

WonderWorker
  • 8,539
  • 4
  • 63
  • 74
Sakal
  • 145
  • 1
  • 2
11

C# 6.0

string mystr = $"This is {strVar}overflow";
Sylvain Rodrigue
  • 4,751
  • 5
  • 53
  • 67
6

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.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
5

Use string.Format:

string mystr = string.Format("This is {0}overflow", "stack");
Sylvain Rodrigue
  • 4,751
  • 5
  • 53
  • 67
Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129
4

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.

Bruno Silva
  • 3,077
  • 18
  • 20
1

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";
  • Under the covers `String.Format()` uses StringBuilder. StringBuilder is typically more efficient when concatenating a lot of strings but the concatenation operator is perfect for one offs. `String.Format()` is useful when formatting needs to be applied to the output, e.g. to add padding or leading zeros to numeric values. So using `String.Format()` in a loop will potentially instantiate a lot of StringBuilders. In that situation it is better to use a single StringBuilder declared outside the loop and `AppendFormat()` inside the loop. – David Clarke Apr 15 '15 at 21:40
0

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

anderly
  • 727
  • 7
  • 16
  • C# has a built in interpolation mechanism. There's absolutely no reason to include a library for this functionality. – Display name Dec 04 '18 at 20:06
  • 3
    @Displayname look at the date on the question. C# didn't always have built-in string interpolation. It was added in C# 6 in 2016. Hence, the reason for my answer in 2014. – anderly Dec 05 '18 at 21:34
0

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

mystr = mystr.Replace("%soverflow", strVar);
Talha Imam
  • 1,046
  • 1
  • 20
  • 22
0

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));
SUNIL DHAPPADHULE
  • 2,755
  • 17
  • 32
0

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

Vikas Lalwani
  • 1,041
  • 18
  • 29
0

You can now create an interpolated string not only with the $ sign, but also with €.

string name = "Michael";

string a = €"Hello, {name}!";
string b = $"Hello, {name}!";

Console.WriteLine(a == b); \/\/ True

The .NET XI version (.NET 11) also promises to introduce support for the £ symbol.

Reference: https://medium.com/@alexeynovikov_89393/all-new-c-13-features-whats-new-in-net-10-and-why-there-is-no-net-9-5ae756f84dc9

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
0

Use:

strVar = "stack"
mystr  = String.Format("This is {0}", strVar);
Phillip Ngan
  • 15,482
  • 8
  • 63
  • 79
-1

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.

Ygalbel
  • 5,214
  • 1
  • 24
  • 32