स्ट्रिंग में विशेष कैरेक्टर (गैर-अल्फान्यूमेरिक) मौजूद हैं या नहीं, यह जांचने के लिए char.IsLetterOrDigit() मेथड का उपयोग किया जाता है।
उदाहरण
using System;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
string str = "Amit$#%";
char[] chars = str.ToCharArray();
char[] specialChars = new char[chars.Length];
int count = 0;
for (int i = 0; i < chars.Length; i++) {
if (!char.IsLetterOrDigit(chars[i])) {
specialChars[count] = chars[i];
count++;
}
}
// सरणी का आकार समायोजित करें
Array.Resize(ref specialChars, count);
Console.WriteLine("Following are the special characters:");
foreach (var item in specialChars) {
Console.WriteLine(item);
}
Console.ReadLine();
}
}
}
आउटपुट
Following are the special characters: $ # %
सरल बूलियन जांच
public static bool HasSpecialChars(string str) {
return str.Any(c => !char.IsLetterOrDigit(c));
}
// उपयोग
bool hasSpecial = HasSpecialChars("Hello!"); // true
bool hasSpecial = HasSpecialChars("Hello"); // false
Regex के साथ
using System.Text.RegularExpressions;
bool hasSpecial = Regex.IsMatch(str, @"[^a-zA-Z0-9]");
// या यूनिकोड-अनुकूल
bool hasSpecial = Regex.IsMatch(str, @"[^\p{L}\p{N}]");
विशिष्ट विशेष कैरेक्टर्स की अनुमति देना
// केवल कुछ विशेष कैरेक्टर्स अनुमत हों string allowedSpecial = "@.-_"; bool valid = str.All(c => char.IsLetterOrDigit(c) || allowedSpecial.Contains(c));
यूनिकोड विचार
char.IsLetterOrDigitयूनिकोड अक्षरों और अंकों को पहचानता है (हिंदी, चीनी, अरबी, आदि)।- यदि केवल ASCII चाहिए:
c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' - श्रेणी जांच:
char.GetUnicodeCategory(c)-UnicodeCategory.Letter,Number,Punctuation,Symbolआदि।
मुख्य बिंदु
char.IsLetterOrDigitसबसे पठनीय और यूनिकोड-सही तरीका है।- Regex पैटर्न
[^a-zA-Z0-9]केवल ASCII के लिए काम करता है। - पासवर्ड वैलिडेशन, इनपुट सैनिटाइजेशन, फाइलनाम वैलिडेशन में उपयोगी।