Zum Fußzeileninhalt springen
.NET HILFE

C# Mehrzeilige Zeichenfolge (Wie es für Entwickler funktioniert)

When you're getting started in C#, strings are one of the earliest concepts you learn. If you’ve ever put together a Hello, World! program, then you’ve already worked with strings.

As you get more familiar with C#, your programs will get more complex. Before long, you’ll start working with strings that span multiple lines. If you’re at that stage now, then you’re in luck, because in this guide, we’ll be explaining what multiline strings are and how to use them. Let’s dive in.

What is a Multiline String?

Multiline strings are exactly what they sound like - a string that spans multiple lines, contrasting to the usual single-line string. A multiline string in C# is created using string literals, which are a series of characters enclosed in double quotes. To form multiline strings, we need to use a special type of string literals called verbatim string literals.

The Magic of Verbatim Strings

To create a multiline string literal in C#, we use verbatim strings. Verbatim strings are prefixed with the @ symbol and allow us to include line breaks, special characters, and even whitespace without using escape sequences.

Here's an example of a multiline string using a verbatim string:

string str = @"This is a
multiline string
in C#.";
string str = @"This is a
multiline string
in C#.";
Dim str As String = "This is a
multiline string
in C#."
$vbLabelText   $csharpLabel

The string str contains three lines, and each line is separated by a line break. Notice the use of the @ symbol to create the verbatim string.

Escaping Characters in Verbatim Strings

There may be cases where you need to include double quotes within a verbatim string. To do this, you have to use double-double quotes. For example:

string str = @"This is a
""multiline""
string in C#.";
string str = @"This is a
""multiline""
string in C#.";
Dim str As String = "This is a
""multiline""
string in C#."
$vbLabelText   $csharpLabel

In this example, the string str contains the word "multiline" enclosed in double quotes, which is achieved by using double-double quotes within the verbatim string.

Concatenating Multiline Strings

You might often need to combine multiline strings with other strings or values. To concatenate a multiline string with other string values, you can use the + operator, just like you would with single-line strings.

string name = "John";
string str = @"Hello, " + name + @",
Welcome to the
world of C# multiline strings!";
string name = "John";
string str = @"Hello, " + name + @",
Welcome to the
world of C# multiline strings!";
Dim name As String = "John"
Dim str As String = "Hello, " & name & ",
Welcome to the
world of C# multiline strings!"
$vbLabelText   $csharpLabel

Here, we’ve concatenated the multiline string with a single line string name.

Formatting Multiline Strings

When working with multiline strings, you can format them with variables or expressions. To format a multiline string, you can use the $ symbol for string interpolation.

int age = 25;
string str = $@"Hello, I am {age} years old,
and I am learning
C# multiline strings!";
int age = 25;
string str = $@"Hello, I am {age} years old,
and I am learning
C# multiline strings!";
Dim age As Integer = 25
Dim str As String = $"Hello, I am {age} years old,
and I am learning
C# multiline strings!"
$vbLabelText   $csharpLabel

We used string interpolation to include the value of the age variable within the multiline string.

Converting Multiline Strings to Single Line Strings

Sometimes, you may need to convert multiline strings into single line strings. To achieve this, you can use the Replace method to replace line breaks with a space or any other desired character.

string multilineString = @"This is a
multiline string
in C#.";

string singleLineString = multilineString.Replace(Environment.NewLine, " ");
string multilineString = @"This is a
multiline string
in C#.";

string singleLineString = multilineString.Replace(Environment.NewLine, " ");
Dim multilineString As String = "This is a
multiline string
in C#."

Dim singleLineString As String = multilineString.Replace(Environment.NewLine, " ")
$vbLabelText   $csharpLabel

We replaced the line breaks in the multiline string with a space, resulting in a single line string.

Handling Long Strings

Sometimes, very long strings can are difficult to read in your code. To make the code more readable, you can split long strings into multiple lines using the + operator.

string longString = "This is a very long string that " +
                    "needs to be split across " +
                    "multiple lines for better readability.";
string longString = "This is a very long string that " +
                    "needs to be split across " +
                    "multiple lines for better readability.";
Dim longString As String = "This is a very long string that " & "needs to be split across " & "multiple lines for better readability."
$vbLabelText   $csharpLabel

We split the long single-line string into three parts and concatenated them using the + operator, making the code more readable.

Creating Multiline String Literals with Raw String Literals

In C# 10, a new feature was introduced called raw string literals. These allow us to create multiline string literals without using the @ symbol. To create a raw string literal, we enclose the string in triple quotes ("""). Raw string literals preserve all the characters, including line breaks, within the triple quotes. For example:

string str = """This is a
multiline string
using raw string literals in C# 10.""";
string str = """This is a
multiline string
using raw string literals in C# 10.""";
Dim str As String = """This is a multiline string using raw string literals in C# 10."""
$vbLabelText   $csharpLabel

We created a multiline string using raw string literals. Notice the use of triple quotes to enclose the string.

Escaping Characters in Raw String Literals

Similar to verbatim strings, we might need to include double quotes within our raw string literals. To do this, we can use double-double quotes. For example:

string str = """This is a
""multiline""
string using raw string literals in C# 10.""";
string str = """This is a
""multiline""
string using raw string literals in C# 10.""";
Dim str As String = """This is a ""multiline"" string using raw string literals in C# 10."""
$vbLabelText   $csharpLabel

We included double quotes within the raw string literal by using double-double quotes.

Combining Verbatim and Raw String Literals

In some cases, we may want to combine the features of both verbatim and raw string literals. This can be done by using the @ symbol followed by triple quotes.

string str = @"""This is a
multiline string
using both verbatim and raw string literals in C# 10.""";
string str = @"""This is a
multiline string
using both verbatim and raw string literals in C# 10.""";
Dim str As String = """This is a
multiline string
using both verbatim and raw string literals in C# 10."""
$vbLabelText   $csharpLabel

In this example, we created a multiline string using both verbatim and raw string literals. Notice the use of the @ symbol followed by triple quotes.

Using Multiline Strings to Generate PDFs in IronPDF

IronPDF is a lightweight .NET PDF library designed specifically with web developers in mind. It makes reading, writing, and manipulating PDF files a breeze, able to convert all kinds of file types into PDF content, and you can use it in your .NET projects for both desktop and web. The best part - it’s free to try out in a development environment.

Here’s how to utilize an HTML multiline string to create a PDF file in IronPDF:

string name = "John";
string age = "25";
string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You are {age} years old.</p>
<p>This is a
multiline string
used to generate a PDF
with IronPDF and dynamic content.</p>
</body>
</html>";

// Create a new PDF document using IronPDF
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(content).SaveAs("c://BioData.pdf");
string name = "John";
string age = "25";
string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You are {age} years old.</p>
<p>This is a
multiline string
used to generate a PDF
with IronPDF and dynamic content.</p>
</body>
</html>";

// Create a new PDF document using IronPDF
var pdfDocument = new IronPdf.ChromePdfRenderer();
pdfDocument.RenderHtmlAsPdf(content).SaveAs("c://BioData.pdf");
Dim name As String = "John"
Dim age As String = "25"
Dim content As String = $"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {name}!</h1>
<p>You are {age} years old.</p>
<p>This is a
multiline string
used to generate a PDF
with IronPDF and dynamic content.</p>
</body>
</html>"

' Create a new PDF document using IronPDF
Dim pdfDocument = New IronPdf.ChromePdfRenderer()
pdfDocument.RenderHtmlAsPdf(content).SaveAs("c://BioData.pdf")
$vbLabelText   $csharpLabel

In this example, we used string interpolation to include the name and age variables within our multiline string, making our PDF content dynamic and customizable. We created a multiline string with the content we wanted in the PDF. We then instantiated the ChromePdfRenderer class from the IronPDF namespace and used the RenderHtmlAsPdf method to convert the multiline string content into a PDF document. Finally, we saved the PDF document to a file called "BioData.pdf".

Conclusion

And that’s a whistlestop tour of the versatile world of multiline strings. Now you’re a multiline string C# pro, you can start implementing them in your projects - such as the example with IronPDF above.

Looking to get your hands on IronPDF? You can start with our 30-day free trial of IronPDF. It’s also completely free to use for development purposes so you can really get to see what it’s made of. And if you like what you see, IronPDF starts as low as $799 for an IronPDF license. For even bigger savings, check out the Iron Suite package where you can get all nine Iron Software tools for the price of two. Happy coding!

Csharp Multiline String 2 related to Conclusion

Häufig gestellte Fragen

Wie können Sie eine mehrzeilige Zeichenfolge in C# erstellen?

In C# können Sie eine mehrzeilige Zeichenfolge mithilfe von wörtlichen Zeichenfolgen erstellen, indem Sie der Zeichenfolge das '@'-Symbol voranstellen. Dadurch können Sie Zeilenumbrüche und Sonderzeichen direkt in der Zeichenfolge einfügen.

Was ist der Zweck der Verwendung von wörtlichen Zeichenfolgen in C#?

Wörtliche Zeichenfolgen in C# werden verwendet, um Zeichenfolgen zu erstellen, die Zeilenumbrüche und Sonderzeichen ohne Escape-Sequenzen behalten. Sie werden durch das '@'-Symbol angegeben und sind ideal zum Schreiben von mehrzeiligen Zeichenfolgen.

Wie handhaben Sie Sonderzeichen wie Anführungszeichen in wörtlichen Zeichenfolgen?

In wörtlichen Zeichenfolgen können Sie Anführungszeichen einschließen, indem Sie doppelte Anführungszeichen verwenden. Beispiel: '@"Dies ist eine ""mehrzeilige"" Zeichenfolge."' erlaubt es Ihnen, Anführungszeichen innerhalb der Zeichenfolge einzufügen.

Was sind rohe Zeichenfolgen in C# 10 und wie funktionieren sie?

Rohe Zeichenfolgen, die in C# 10 eingeführt wurden, ermöglichen die Erstellung von mehrzeiligen Zeichenfolgen ohne das '@'-Symbol. Sie werden mit dreifachen Anführungszeichen eingeschlossen und behalten alle Zeichen, einschließlich Zeilenumbrüche, genau so, wie sie erscheinen.

Wie können mehrzeilige Zeichenfolgen bei der PDF-Erstellung verwendet werden?

Mehrzeilige Zeichenfolgen können verwendet werden, um dynamische Inhalte im HTML-Format zu erstellen, die dann mit Bibliotheken wie IronPDF, die die Umwandlung von HTML in PDF unterstützen, in PDF-Dokumente konvertiert werden können.

Was ist Zeichenfolgeninterpolation und wie wird sie auf mehrzeilige Zeichenfolgen angewendet?

Zeichenfolgeninterpolation in C# ermöglicht das Einbetten von Variablen oder Ausdrücken innerhalb von Zeichenfolgen mit dem '$'-Symbol. Sie kann mit mehrzeiligen Zeichenfolgen verwendet werden, um dynamische Inhalte nahtlos einzufügen.

Wie konvertieren Sie eine mehrzeilige Zeichenfolge in eine einzeilige Zeichenfolge in C#?

Um eine mehrzeilige Zeichenfolge in eine einzeilige Zeichenfolge zu konvertieren, können Sie die Replace-Methode verwenden, um Zeilenumbrüche durch Leerzeichen oder ein anderes Zeichen zu ersetzen. Beispiel: multilineString.Replace(Environment.NewLine, " ").

Warum sollten Entwickler Bibliotheken für die PDF-Erstellung in .NET-Anwendungen verwenden?

Bibliotheken, die für die PDF-Erstellung in .NET entwickelt wurden, wie IronPDF, vereinfachen den Prozess des Lesens, Schreibens und Manipulierens von PDFs. Sie unterstützen die Umwandlung verschiedener Dateitypen in PDFs und bieten ein leistungsfähiges Toolset für Desktop- und Webanwendungen.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen