在 C# 中從字串中刪除引號

Muhammad Maisam Abbas 2024年2月16日
在 C# 中從字串中刪除引號

本教程將介紹從 C# 中的字串變數中刪除引號的方法。

使用 C# 中的 String.Replace() 函式從字串中刪除引號

String.Replace(x, y) 函式用於將 C# 主字串內的所有出現的字串 x 替換為字串 yString.Replace() 函式具有字串返回型別。如果要刪除字串中的引號,可以將其替換為空字串。我們可以指定要用"\""替換雙引號。下面的程式碼示例向我們展示瞭如何使用 C# 中的 String.Replace() 函式從字串中刪除引號。

using System;

namespace remove_quotes_from_string {
  class Program {
    static void method1() {
      string str = "He said \"This is too soon for me\" and left.";
      Console.WriteLine(str);
      string newstr = str.Replace("\"", "");
      Console.WriteLine(newstr);
    }
    static void Main(string[] args) {
      method1();
    }
  }
}

輸出:

He said "This is too soon for me" and left.
He said This is too soon for me and left.

在上面的程式碼中,我們用 C# 中的 str.Replace() 函式用空字串替換了引號,從而刪除了字串變數 str 中的引號。我們使用\轉義字元在另一對雙引號中編寫了雙引號。

Muhammad Maisam Abbas avatar Muhammad Maisam Abbas avatar

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

LinkedIn

相關文章 - Csharp String