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

How to Convert C# Strings to Escaped String Literals?

Barbara Streisand
Release: 2025-01-28 00:46:10
Original
576 people have browsed it

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:

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();
        }
    }
}
Copy after login
The output result is:

var input = "\tHello\r\n\tWorld!";
Copy after login
Use Roslyn's alternative method:

<code>"\tHello\r\n\tWorld!"</code>
Copy after login
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:
private static string ToLiteral(string valueTextForCompiler)
{
    return Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(valueTextForCompiler, false);
}
Copy after login

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