I want to do the following in C# (coming from a Python background):
strVar = \"stack\"
mystr = \"This is %soverflow\" % (strVar)
How do I
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();
Use string.Format
:
string mystr = string.Format("This is {0}overflow", "stack");
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.
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";
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));
C# 6.0
string mystr = $"This is {strVar}overflow";