在c#中,我可以将字符串值转换为字符串文字,我将在代码中看到它的方式吗?我想用转义序列替换制表符,换行符等。
如果这段代码:
Console.WriteLine(someString);
生产:
Hello
World!
我想要这样的代码:
Console.WriteLine(ToLiteral(someString));
生产:
\tHello\r\n\tWorld!\r\n
在c#中,我可以将字符串值转换为字符串文字,我将在代码中看到它的方式吗?我想用转义序列替换制表符,换行符等。
如果这段代码:
Console.WriteLine(someString);
生产:
Hello
World!
我想要这样的代码:
Console.WriteLine(ToLiteral(someString));
生产:
\tHello\r\n\tWorld!\r\n
当前回答
Hallgrim的回答很好,但是“+”,换行和缩进的添加破坏了我的功能。一个简单的解决方法是:
private static string ToLiteral(string input)
{
using (var writer = new StringWriter())
{
using (var provider = CodeDomProvider.CreateProvider("CSharp"))
{
provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, new CodeGeneratorOptions {IndentString = "\t"});
var literal = writer.ToString();
literal = literal.Replace(string.Format("\" +{0}\t\"", Environment.NewLine), "");
return literal;
}
}
}
其他回答
有趣的问题。
如果你找不到更好的方法,你可以随时替换。 如果你选择它,你可以使用这个c#转义序列列表:
\' - single quote, needed for character literals \" - double quote, needed for string literals \ - backslash \0 - Unicode character 0 \a - Alert (character 7) \b - Backspace (character 8) \f - Form feed (character 12) \n - New line (character 10) \r - Carriage return (character 13) \t - Horizontal tab (character 9) \v - Vertical quote (character 11) \uxxxx - Unicode escape sequence for character with hex value xxxx \xn[n][n][n] - Unicode escape sequence for character with hex value nnnn (variable length version of \uxxxx) \Uxxxxxxxx - Unicode escape sequence for character with hex value xxxxxxxx (for generating surrogates)
这个列表可以在c#常见问题中找到 有哪些字符转义序列可用?
使用Regex.Escape(字符串):
正则表达式。Escape转义最小字符集(,*,+,?,|,{,[, (,), ^, $,。, #和空白),用转义符替换它们 代码。
以下是对Smilediver的回答的一点改进。它不会转义所有的no-ASCII字符,但只有这些是真正需要的。
using System;
using System.Globalization;
using System.Text;
public static class CodeHelper
{
public static string ToLiteral(this string input)
{
var literal = new StringBuilder(input.Length + 2);
literal.Append("\"");
foreach (var c in input)
{
switch (c)
{
case '\'': literal.Append(@"\'"); break;
case '\"': literal.Append("\\\""); break;
case '\\': literal.Append(@"\\"); break;
case '\0': literal.Append(@"\0"); break;
case '\a': literal.Append(@"\a"); break;
case '\b': literal.Append(@"\b"); break;
case '\f': literal.Append(@"\f"); break;
case '\n': literal.Append(@"\n"); break;
case '\r': literal.Append(@"\r"); break;
case '\t': literal.Append(@"\t"); break;
case '\v': literal.Append(@"\v"); break;
default:
if (Char.GetUnicodeCategory(c) != UnicodeCategory.Control)
{
literal.Append(c);
}
else
{
literal.Append(@"\u");
literal.Append(((ushort)c).ToString("x4"));
}
break;
}
}
literal.Append("\"");
return literal.ToString();
}
}
一个更结构化的方法,包括字符串和字符的所有转义序列,是:
它不会用对应的文字替换Unicode字符。它也不能煮鸡蛋。
public class ReplaceString
{
static readonly IDictionary<string, string> m_replaceDict
= new Dictionary<string, string>();
const string ms_regexEscapes = @"[\a\b\f\n\r\t\v\\""]";
public static string StringLiteral(string i_string)
{
return Regex.Replace(i_string, ms_regexEscapes, match);
}
public static string CharLiteral(char c)
{
return c == '\'' ? @"'\''" : string.Format("'{0}'", c);
}
private static string match(Match m)
{
string match = m.ToString();
if (m_replaceDict.ContainsKey(match))
{
return m_replaceDict[match];
}
throw new NotSupportedException();
}
static ReplaceString()
{
m_replaceDict.Add("\a", @"\a");
m_replaceDict.Add("\b", @"\b");
m_replaceDict.Add("\f", @"\f");
m_replaceDict.Add("\n", @"\n");
m_replaceDict.Add("\r", @"\r");
m_replaceDict.Add("\t", @"\t");
m_replaceDict.Add("\v", @"\v");
m_replaceDict.Add("\\", @"\\");
m_replaceDict.Add("\0", @"\0");
//The SO parser gets fooled by the verbatim version
//of the string to replace - @"\"""
//so use the 'regular' version
m_replaceDict.Add("\"", "\\\"");
}
static void Main(string[] args){
string s = "here's a \"\n\tstring\" to test";
Console.WriteLine(ReplaceString.StringLiteral(s));
Console.WriteLine(ReplaceString.CharLiteral('c'));
Console.WriteLine(ReplaceString.CharLiteral('\''));
}
}
我试图将ToVerbatim添加到Hallgrim公认的答案中:
private static string ToLiteral(string input)
{
using (var writer = new StringWriter())
{
using (var provider = CodeDomProvider.CreateProvider("CSharp"))
{
provider.GenerateCodeFromExpression(new CodePrimitiveExpression(input), writer, new CodeGeneratorOptions { IndentString = "\t" });
var literal = writer.ToString();
literal = literal.Replace(string.Format("\" +{0}\t\"", Environment.NewLine), "");
return literal;
}
}
}
private static string ToVerbatim(string input)
{
string literal = ToLiteral(input);
string verbatim = "@" + literal.Replace(@"\r\n", Environment.NewLine);
return verbatim;
}