ให้เรานำเราต้องกำจัดตัวแบ่งบรรทัด ช่องว่าง และพื้นที่แท็บจากสตริงด้านล่าง
กำจัด.jpg
ตัวอย่าง
เราสามารถใช้วิธีส่วนขยาย Replace() ของสตริงเพื่อทำสิ่งนี้ได้
using System;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
string testString = "Hello \n\r beautiful \n\t world";
string replacedValue = testString.Replace("\n\r", "_").Replace("\n\t", "_");
Console.WriteLine(replacedValue);
Console.ReadLine();
}
}
} ผลลัพธ์
ผลลัพธ์ของโค้ดด้านบนคือ
Hello _ beautiful _ world
ตัวอย่าง
เรายังสามารถใช้ Regex เพื่อดำเนินการเดียวกันได้ Regex พร้อมใช้งานในเนมสเปซ System.Text.RegularExpressions
using System;
using System.Text.RegularExpressions;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
string testString = "Hello \n\r beautiful \n\t world";
string replacedValue = Regex.Replace(testString, @"\n\r|\n\t", "_");
Console.WriteLine(replacedValue);
Console.ReadLine();
}
}
} ผลลัพธ์
ผลลัพธ์ของโค้ดด้านบนคือ
Hello _ beautiful _ world