I would like to check, in C#, if a char contains a non-ASCII character. What is the best way to check for special characters such as 志 or Ω?
Asked
Active
Viewed 2.9k times
37
Alexandru
- 11,618
- 16
- 103
- 198
-
2http://social.msdn.microsoft.com/Forums/vstudio/en-US/bcdfb967-aa97-4d26-9daa-d20829f805b9/detect-nonascii-characters – Zaki Sep 03 '13 at 15:39
-
1you can also use regex http://stackoverflow.com/questions/123336/how-can-you-strip-non-ascii-characters-from-a-string-in-c – Zaki Sep 03 '13 at 15:40
2 Answers
46
ASCII ranges from 0 - 127, so just check for that range:
char c = 'a';//or whatever char you have
bool isAscii = c < 128;
musefan
- 46,935
- 21
- 128
- 175
-
14And for those who want to be fancy, `bool isAscii = c <= sbyte.MaxValue;`. – Jeppe Stig Nielsen Sep 03 '13 at 16:57
37
bool HasNonASCIIChars(string str)
{
return (System.Text.Encoding.UTF8.GetByteCount(str) != str.Length);
}
Wai Ha Lee
- 8,173
- 68
- 59
- 86
Malik Khalil
- 5,827
- 2
- 37
- 32