Home >Backend Development >C++ >How to Convert C# Strings to Escaped String Literals?

How to Convert C# Strings to Escaped String Literals?

Barbara Streisand
Barbara StreisandOriginal
2025-01-28 00:46:10578browse

Convert the C#string to a rigid string character

How to Convert C# Strings to Escaped String Literals?

Question:

Can the C#string value be converted into a string with a string containing a rotary sequence, such as the symbol and changing line? For example, convert the string containing the formula and the trading symbols into string containing the rotary sequence "T" and "RN"?

Answer:

Traditional method:

have been using one method for a long time:

Use this method, you can convert the following string:

<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>
The output result is:

<code class="language-csharp">var input = "\tHello\r\n\tWorld!";</code>
Use Roslyn's alternative method:

<code>"\tHello\r\n\tWorld!"</code>
The newer method involves Microsoft.Codeanalysis.csharp package from Nuget. The following is the updated code:

Using this method, you can get the same results as the previous method, and change the following string:

The output result is:
<code class="language-csharp">private static string ToLiteral(string valueTextForCompiler)
{
    return Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(valueTextForCompiler, false);
}</code>

The above is the detailed content of How to Convert C# Strings to Escaped String Literals?. 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