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