写入文本文件时如何转义特殊字符

时间:2019-04-04 21:55:18

标签: c#

我正在读取此字符串

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 ? 

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

例如:

mounted() {
  document.onreadystatechange = () => {
    if (document.readyState == "complete") {
      console.log('Page completed with image and files!')

      // HOW LOAD COMPONENTS HERE?
      this.readyStateComplete = true

    }
  }
},

将为您提供所需的结果。但是请注意,这仅在引号之间有实际的字符串文本时才有效,而对变量不起作用。

也请看一下这个问题及其答案:Can I convert a C# string value to an escaped string literal