Detect Junk Characters in string
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
开发者_如何学C 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...
You can make regular expression which allowed all the desired characters and use it for each strings. I think this will improve the performance. All you have to do is to create a proper regular expression.
Update: However, Using RegEx will not improve the speed it will just minimize the code lines.
精彩评论