ภาพรวม
ใช้ String.Replace แทนที่อักขระพิเศษ (special characters) ในสตริง เช่น $, #, @, ฯลฯ
โค้ดตัวอย่าง
using System;
public class Program {
public static void Main() {
string str = "abcd$ef$gh";
Console.WriteLine($"Original: '{str}'");
// แทนที่ $ ด้วย k
string result = str.Replace('$', 'k');
Console.WriteLine($"Replaced: '{result}'");
// แทนที่หลายตัวพร้อมกัน (Chaining)
string str2 = "a@b#c$d%e";
string result2 = str2
.Replace("@", "")
.Replace("#", "")
.Replace("$", "")
.Replace("%", "");
Console.WriteLine($"Remove special chars: '{result2}'"); // abcde
}
}
ผลลัพธ์
Original: 'abcd$ef$gh'
Replaced: 'abcdkefkgh'
Remove special chars: 'abcde'
วิธีที่ดีกว่า: Regular Expression
using System.Text.RegularExpressions;
string str = "a@b#c$d%e^f&g*h";
// ลบอักขระพิเศษทั้งหมด (เก็บแค่ alphanumeric)
string cleaned = Regex.Replace(str, @"[^a-zA-Z0-9]", "");
Console.WriteLine($"Alphanumeric only: '{cleaned}'"); // abcdefgh
// แทนที่อักขระพิเศษด้วยตัวแทน
string replaced = Regex.Replace(str, @"[^a-zA-Z0-9]", "_");
Console.WriteLine($"Replaced with _: '{replaced}'"); // a_b_c_d_e_f_g_h
ลบอักขระควบคุม (Control Characters) และ Whitespace
string dirty = "Hello\tWorld\n\rGoodbye";
string clean = new string(dirty.Where(c => !char.IsControl(c)).ToArray());
Console.WriteLine(clean); // HelloWorldGoodbye
// หรือ Regex
string clean2 = Regex.Replace(dirty, @"\p{C}", ""); // Unicode control chars
Normalize Unicode (Thai, Emoji, etc.)
string thai = "สวัสดีครับ";
// ไม่ต้อง Replace อะไร - Unicode ทำงานได้ปกติ
string withEmoji = "Hello 🌍 World!";
string noEmoji = Regex.Replace(withEmoji, @"\p{So}", ""); // Symbol, Other (emoji)
Console.WriteLine(noEmoji); // Hello World!
Performance: StringBuilder สำหรับหลายครั้ง
using System.Text;
StringBuilder sb = new StringBuilder(1000);
for (int i = 0; i < 100; i++) {
sb.Append($"Item{i}$");
}
string result = sb.ToString().Replace("$", "-");
// หรือ
sb.Replace('$', '-'); // StringBuilder.Replace มี overload เหมือน String