Detection of unwanted characters in a string

I want to allow the user to enter characters, numbers, and special characters, but not JUNK characters (e.g. ♠ ♣, etc.) whose ascii value is greater than 127.

I have a 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 the code bit slower as I have to compare each line and its character. Can anyone suggest a better approach?

+5
source share
2 answers

Well, on the one hand, 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 non-ASCII characters are:

bool bad = value.Any(c => c < 32 || c > 126);

... but in principle, you cannot detect non-ASCII characters without repeating each character in the string ...

+8
source

, . , . , , .

: RegEx , .

+1

All Articles