C#, the string converts the string into a rotary string in the word
In C#, how to convert the string value into a string character with a rotary sequence, such as the symbol and the change symbols?
Assuming we have the following code:
The output result is:
<code class="language-c#">Console.WriteLine(someString);</code>
We want to create a
<code>Hello World!</code>
ToLiteral
<code>\tHello\r\n\tWorld!\r\n</code>
Method 1: Use CodedomProvider
In the past, the solution involved the use of in the name space, as shown in the following code:
System.CodeDom.Compiler
Method 2: Use the microSoft.codeanalysis.csharp bag of Roslyn
CodeDomProvider
Recently, Graham High found that we can use Roslyn's microsoft.codeanalysis.csharp Nuget package to achieve the same results:
<code class="language-c#">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>
This method directly uses the functions provided by the Roslyn library, which is more concise and efficient.
The above is the detailed content of How Can I Convert a C# String to an Escaped String Literal?. For more information, please follow other related articles on the PHP Chinese website!