Reputation: 33
Say I have the following
string = "make {0}{1} in {2} to produce {0}{1} in {2} minutes";
This pulls the correct values for {0}
{1}
{2}
which works fine, for the second {0}
{1}
I want to divide the value for {0}
by 2.
What is the best way to do this?
Upvotes: 0
Views: 71
Reputation: 6961
It is string interpolation
Microsoft suggest to use "$" character to interpolate strings. This make code more readable and concise. A basic usage is like this :
double speedOfLight = 299792.458;
string message = $"The speed of light is {speedOfLight} km/s.";
In your case it should be :
string result = $"make {0/2}{1} in {2} to produce {0/2}{1} in {2} minutes";
The $ special character identifies a string literal as an interpolated string. An interpolated string is a string literal that might contain interpolation expressions. When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results. This feature is available starting with C# 6.
String interpolation provides a more readable and convenient syntax to create formatted strings than a
string composite formatting
feature.
Upvotes: 0
Reputation: 5512
You can use something like this.
string = $"make {var1}{var2} in {var3} to produce {var1/2}{var2} in {var3} minutes";
If that does not work due to language version restrictions, it can be done through string.Format()
like this:
string = string.Format("make {0}{1} in {2} to produce {3}{1} in {2} minutes", var1, var2, var3, var1/2);
Upvotes: 1
Reputation: 151674
It's called a format string and not a calculation string.
So you'll have to do the calculation yourself, causing the positional arguments to increment in number (3 in this case):
string = string.Format("make {0}{1} in {2} to produce {3}{1} in {2} minutes",
val0, val1, val2, val0 / 2);
Upvotes: 2