ใช้ Char.IsLetterOrDigit() ตรวจสอบว่าเป็นตัวอักษรหรือตัวเลข ถ้าไม่ใช่ = อักขระพิเศษ
ตัวอย่างโค้ดเต็ม
using System;
namespace Demo {
class myApplication {
static void Main(string[] args) {
string str = "Amit$#%";
char[] chars = str.ToCharArray();
List specialChars = new List();
for (int i = 0; i < chars.Length; i++) {
if (!Char.IsLetterOrDigit(chars[i])) {
specialChars.Add(chars[i]);
}
}
Console.WriteLine("Following are the special characters:");
foreach (var ch in specialChars) {
Console.WriteLine(ch);
}
Console.ReadLine();
}
}
}
ผลลัพธ์
Following are the special characters: $ # %
คำอธิบาย: โค้ดต้นฉบับใช้ Array.Resize ซับซ้อน ผมปรับปรุงใช้ List<char> แทน ง่ายกว่าและมีประสิทธิภาพดีกว่า
หมายเหตุ: Char.IsLetterOrDigit คืน true สำหรับตัวอักษรทุกภาษา (Unicode) และตัวเลข 0-9