C# 程式來移除字串的末尾部分


在 C# 中使用 Regex.Replace 方法來移除字串的末尾部分。

以下面字串為例 −

string s1 = "Demo Text!";

現在,假設你需要從字串中移除感嘆號(!) 。只需使用 replace 將其設定為為空即可 −

System.Text.RegularExpressions.Regex.Replace(s1, "!", "");

以下為完整程式碼 −

示例

 線上演示

using System;
using System.Text.RegularExpressions;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         string s1 = "Demo Text!";
         // replace the end part
         string s2 = System.Text.RegularExpressions.Regex.Replace(s1, "!", "");
         Console.WriteLine("\"{0}\"
\"{1}\"", s1, s2);       }    } }

輸出

"Demo Text!"
"Demo Text"

更新日期: 22-6 月-2020

473 次瀏覽

啟動您的 職業

完成課程獲取證書

開始
廣告
© . All rights reserved.