Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiline string with added text from variables

Tags:

c#

I am aware this will work:

string multiline_text = @"this is a multiline text this is line 1 this is line 2 this is line 3"; 

How can I make the following work:

string a1 = " line number one"; string a2 = " line number two"; string a3 = " line number three";  string multiline_text = @"this is a multiline text this is " + a1 + "  this is " + a2 + "  this is " + a3 + "; 

Is it possible without splitting the string into several substring, one for each line?

like image 745
enb081 Avatar asked Apr 24 '13 15:04

enb081


People also ask

How do you pass a variable to a multiline string in Python?

In Python, you have different ways to specify a multiline string. You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines. Moreover, backslash works as a line continuation character in Python.

How do I create a multiline string in JavaScript?

There are three ways to create strings that span multiple lines: By using template literals. By using the + operator – the JavaScript concatenation operator. By using the \ operator – the JavaScript backslash operator and escape character.

How do you make a multi line string in C#?

Use the verbatim symbol to write a multiline string literal in C# Copy string verbatim = @" "; The program below shows how we can use the @ symbol to write a multiline string.

How do you echo a multiline string?

Use echo With the -e Option to Make Multi-Line String in Bash. The following bash script prints the words to multiline. txt without any extra spaces. The -e option enables the interpretation of escape characters in the variable greet .


2 Answers

One option is to use string formatting instead. Before C# 6:

string pattern = @"this is a multiline text this is {0} this is {1} this is {2}";  string result = string.Format(pattern, a1, a2, a3); 

With C# 6, you can use an interpolated verbatim string literal:

string pattern = $@"this is a multiline text this is {a1} this is {a2} this is {a3}"; 

Note that $@ has to be exactly that - if you try to use @$, it won't compile.

like image 74
Jon Skeet Avatar answered Nov 07 '22 14:11

Jon Skeet


Although string.Format is better practice, to do what you're trying to achieve, just add the extra @s at the end of each line:

string multiline_text = @"this is a multiline text this is " + a1 + @"  this is " + a2 + @"  this is " + a3 + @""; 

You were also missing a last " before the ending semi colon.

like image 39
mattytommo Avatar answered Nov 07 '22 14:11

mattytommo