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

How to Escape String Literals in C#?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-28 01:01:08802browse

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>

Expected output:

<code>\tHello\r\n\tWorld!\r\n</code>

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>

Example:

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

Output:

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

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>

Example:

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

Output:

<code>"\tHello\r\n\tWorld!"</code>

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!

Statement:
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