In C#, how can I detect if a character is a non-ASCII character?
Solution 1
ASCII ranges from 0 - 127, so just check for that range:
char c = 'a';//or whatever char you have
bool isAscii = c < 128;
Solution 2
bool HasNonASCIIChars(string str)
{
return (System.Text.Encoding.UTF8.GetByteCount(str) != str.Length);
}
Alexandru
"To avoid criticism, say nothing, do nothing, be nothing." - Aristotle "It is wise to direct your anger towards problems - not people; to focus your energies on answers - not excuses." - William Arthur Ward "Science does not know its debt to imagination." - Ralph Waldo Emerson "Money was never a big motivation for me, except as a way to keep score. The real excitement is playing the game." - Donald Trump "All our dreams can come true, if we have the courage to pursue them." - Walt Disney "Mitch flashes back to a basketball game held in the Brandeis University gymnasium in 1979. The team is doing well and chants, 'We're number one!' Morrie stands and shouts, 'What's wrong with being number two?' The students fall silent." - Tuesdays with Morrie
Updated on October 30, 2021Comments
-
Alexandru over 2 years
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Ω
? -
Jeppe Stig Nielsen over 10 yearsAnd for those who want to be fancy,
bool isAscii = c <= sbyte.MaxValue;
. -
Vesk almost 3 yearsNow that's an interesting way to go about this. Really clever!