【问题标题】:How to escape special chars when writing into a text file [duplicate]写入文本文件时如何转义特殊字符[重复]
【发布时间】:2019-04-04 21:55:18
【问题描述】:

我正在阅读这个字符串

string input = "Hello, my name is \t Peter \n how are you ? ";

我在我的文件中打印这个:

Hello, my name is      Peter
how are you? 

我希望结果是:

Hello, my name is \t Peter \n how are you ? 

在写入文件文本时如何转义制表符和换行符等特殊字符?

【问题讨论】:

  • "..... \\t ...."@".... \t ....."

标签: c#


【解决方案1】:
string input = "Hello, my name is \t Peter \n how are you ? ";
input = input.Replace("\n","\\n");

你可以对其他人做同样的事情,比如 \t, ...

What character escape sequences are available?

Live Demo

【讨论】:

  • 谢谢,我一试就标记!
  • 你知道如何用 \ 替换 \\ 我试过 string result = input.Replace(@"\","\\");但它没有用
【解决方案2】:

另一种选择是通过添加@ 字符将您的字符串视为文字字符串。 (https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim)

例如:

string s = @"Hello, my name is \t Peter \n how are you ? ";
Console.WriteLine(s);

会给你你正在寻找的结果。但是请注意,这仅适用于引号之间的实际字符串文本并且不适用于变量。

还可以看看这个问题及其答案:Can I convert a C# string value to an escaped string literal

【讨论】:

  • 他说他正在读取它(可能从文件中),它不是硬编码的
猜你喜欢
  • 2018-09-29
  • 2012-10-09
  • 2018-05-22
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 2012-03-25
  • 2021-01-18
相关资源
最近更新 更多