Home > Backend Development > C++ > How to Escape String Literals in C#?

How to Escape String Literals in C#?

Patricia Arquette
Release: 2025-01-28 01:01:08
Original
794 people have browsed it

How to Escape String Literals in C#?

Convert string value to string literal with escape sequence in C#

In C#, you can convert a string value to a string literal with escape sequences using the following technique:

Original code:

<code class="language-csharp">Console.WriteLine(someString);</code>
Copy after login

Expected output:

<code>\tHello\r\n\tWorld!\r\n</code>
Copy after login

Method 1: Use C# StringWriter and CodeDomProvider

<code class="language-csharp">private static string ToLiteral(string input)
{
    using (var writer = new StringWriter())
    {
        using (var provider = CodeDomProvider.CreateProvider("CSharp"))
        {
            provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, null);
            return writer.ToString();
        }
    }
}</code>
Copy after login

Example:

<code class="language-csharp">var input = "\tHello\r\n\tWorld!";
Console.WriteLine(input);
Console.WriteLine(ToLiteral(input));</code>
Copy after login

Output:

<code>    Hello
    World!
"\tHello\r\n\tWorld!"</code>
Copy after login

Method 2: Use Roslyn’s Microsoft.CodeAnalysis.CSharp package

<code class="language-csharp">private static string ToLiteral(string valueTextForCompiler)
{
    return Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(valueTextForCompiler, false);
}</code>
Copy after login

Example:

<code class="language-csharp">Console.WriteLine(ToLiteral("\tHello\r\n\tWorld!"));</code>
Copy after login

Output:

<code>"\tHello\r\n\tWorld!"</code>
Copy after login

The above is the detailed content of How to Escape String Literals in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template