HOWTO · Csharp

在 C# 中轉義雙引號

有兩種主要方法可用於在 C# 中轉義雙引號。

本教程將討論在 C# 中轉義雙引號的方法。

在 C# 中使用""轉義符轉義雙引號

如果要儲存像 He said, "Hi"這樣的字串,則必須在 C# 中使用雙引號轉義符""。我們必須將雙引號括在另一對雙引號內,例如""Hi"",以將其儲存在像"Hi"這樣的字串變數中。下面的程式碼示例向我們展示瞭如何使用 C# 中的""轉義字元轉義雙引號。

using System;

namespace escape_quotes {
  class Program {
    static void Main(string[] args) {
      string msg = @"He said ""Hi""";
      Console.WriteLine(msg);
    }
  }
}

輸出:

He said "Hi"

通過在 C# 中使用""轉義字元,我們將字串 msg 儲存為值 He said "Hi"

用 C# 中的\轉義符轉義雙引號

我們還可以使用\轉義字元將字串 He said "Hi"儲存在 C# 的字串變數中。我們必須在每個雙引號之前都寫一個\,例如 He said \"Hi\"。下面的程式碼示例向我們展示瞭如何使用 C# 中的\轉義字元轉義雙引號。

using System;

namespace escape_quotes {
  class Program {
    static void Main(string[] args) {
      string msg = "He said \"Hi\"";
      Console.WriteLine(msg);
    }
  }
}

輸出:

He said "Hi"

通過在 C# 中使用\轉義字元,我們將字串 msg 儲存為值 He said "Hi"