可以将C#字符串值转换为转义字符串文本吗?在C#中,我是否可以将字符串值转换为字符串文本,就像我在代码中所看到的那样?我想用转义序列替换制表符、换行符等。如果此代码:Console.WriteLine(someString);生产:HelloWorld!我要这个密码:Console.WriteLine(ToLiteral(someString));生产:\tHello\r\n\tWorld!\r\n
3 回答
九州编程
TA贡献1785条经验 获得超4个赞
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(); } }}
var input = "\tHello\r\n\tWorld!";Console.WriteLine(input);Console.WriteLine(ToLiteral(input));
Hello World!"\tHello\r\n\tWorld!"
ibeautiful
TA贡献1993条经验 获得超5个赞
string
char
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('\'')); }}
- 3 回答
- 0 关注
- 1772 浏览
添加回答
举报
0/150
提交
取消