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 3.6k times
42

Alexandru
- 12,264
- 17
- 113
- 208
-
2http://social.msdn.microsoft.com/Forums/vstudio/en-US/bcdfb967-aa97-4d26-9daa-d20829f805b9/detect-nonascii-characters – Zaki Sep 03 '13 at 15:39
-
2you 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
3 Answers
50
ASCII ranges from 0 - 127, so just check for that range:
char c = 'a';//or whatever char you have
bool isAscii = c < 128;

musefan
- 47,875
- 21
- 135
- 185
-
17And for those who want to be fancy, `bool isAscii = c <= sbyte.MaxValue;`. – Jeppe Stig Nielsen Sep 03 '13 at 16:57
49
bool HasNonASCIIChars(string str)
{
return (System.Text.Encoding.UTF8.GetByteCount(str) != str.Length);
}

Wai Ha Lee
- 8,598
- 83
- 57
- 92

Malik Khalil
- 6,454
- 2
- 39
- 33
9
Just in case anybody comes across this. In dotNET6 there is a new method to check whether a character is an ASCII character or not
public static bool IsAscii (char c);
To solve the issue, you can just write
var containsOnlyAscii = str.All(char.IsAscii);
using the LINQ All
method.
In general, you can use this new method to check individual characters
var isAscii = char.IsAscii(c);

Crown
- 169
- 1
- 7