How do I detect non-printable characters in .NET?

Viewed 33537

I'm just wondering if there is a method in .NET 2.0 that checks whether a character is printable or not – something like isprint(int) from standard C.

I found Char.IsControl(Char).

Could that be used for this purpose?

4 Answers

In addition to Char.IsControlChar() there are several other functions that can be used to determine what category a given char value is:

  • IsLetter()
  • IsNumber()
  • IsDigit()
  • IsLetterOrDigit()
  • IsSymbol()
  • IsPunctuation()
  • IsSeparator()
  • IsWhiteSpace()

If what you have is a "traditional ASCII text" file, and you want to use supplied functions, the expression:

(Char.IsLetterOrDigit(ch) || Char.IsPunctuation(ch) || Char.IsSymbol(ch) || (ch==' '))

should work.

Now, if you are working with Unicode, you are opening a can or worms. Even back in the day, whether a space is printable or not printable was open to interpretation (hence the isprint() and isgraph() functions). See this related question and answers about "printable" unicode characters.

Related