I want to allow user to enter characters,numbers and special characters but no the JUNK Characters (ex. ♠ ♣ etc) whose ascii value is greater thane 127.
I have function like this
            for (int i = 0; i < value.Length; i++) // value is input string
            {
                if ((int)value[i] < 32 || (int)value[i] > 126)
                {
                         // show error
                 }
            }
This makes code bit slower as i have to compare each and every string and its character. Can anyone suggest better approach ?
Well, for one thing you can make the code simpler:
foreach (char c in value)
{
    if (c < 32 || c > 126)
    {
        ...
    }
}
Or using LINQ, if you just need to know if any characters are non-ASCII:
bool bad = value.Any(c => c < 32 || c > 126);
... but fundamentally you're not going to be able to detect non-ASCII characters without iterating over every character in the string...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With