Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert variable values in the middle of a string

Tags:

string

c#

In C#: If I want to create a message like this: "Hi We have these flights for you: Flight A,B,C,D. Which one do you want"

where just the section in bold is dynamic and I pass its value at run time, but its left and right parts are fixed. I can create something like LeftMessage + those variables + RightMessage to create this. But I was wondering if there is a way of doing it all at once without the need to create two separate left and right messages?

For translation purposes I am putting those left and right messages inside string resources so now I have two separate string resources. Is there a way to do it all at once?

like image 957
DarkNightFan Avatar asked Oct 23 '12 15:10

DarkNightFan


People also ask

How do you pass a variable inside a string in C#?

In C# 6 you can use string interpolation: string name = "John"; string result = $"Hello {name}"; The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked. Show activity on this post.

Which one allows us to insert variables into the string?

The + operator allows us to concatenate strings, that is, to join strings together.

How do you put a variable inside a string in Python?

If you can depend on having Python >= version 3.6, then you have another attractive option, which is to use the new formatted string literal (f-string) syntax to insert variable values. An f at the beginning of the string tells Python to allow any currently valid variable names as variable names within the string.


1 Answers

There's now (C# 6) a more succinct way to do it: string interpolation.

From another question's answer:

In C# 6 you can use string interpolation:

string name = "John"; string result = $"Hello {name}"; 

The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.

like image 106
Vimes Avatar answered Sep 24 '22 15:09

Vimes