ใช้วิธี Regex.Replace เพื่อลบส่วนท้ายของสตริงใน C #
ต่อไปนี้เป็นสตริง −
string s1 = "Demo Text!";
ตอนนี้ สมมติว่าคุณต้องลบเครื่องหมายอัศเจรีย์ (!) ออกจากสตริง สำหรับสิ่งนั้นเพียงแค่ตั้งค่าเป็นโมฆะโดยใช้การแทนที่ −
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}\"\n\"{1}\"", s1, s2);
}
}
} ผลลัพธ์
"Demo Text!" "Demo Text"