Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect Junk Characters in string

Tags:

string

c#

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 ?

like image 992
Sangram Nandkhile Avatar asked Aug 31 '11 08:08

Sangram Nandkhile


1 Answers

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...

like image 122
Jon Skeet Avatar answered Sep 30 '22 14:09

Jon Skeet