37

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 Ω?

Alexandru
  • 11,618
  • 16
  • 103
  • 198
  • 2
    http://social.msdn.microsoft.com/Forums/vstudio/en-US/bcdfb967-aa97-4d26-9daa-d20829f805b9/detect-nonascii-characters – Zaki Sep 03 '13 at 15:39
  • 1
    you 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 Answers2

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