How do I get a list of all the printable characters in C#?

后端 未结 5 730
我寻月下人不归
我寻月下人不归 2020-12-18 19:10

I\'d like to be able to get a char array of all the printable characters in C#, does anybody know how to do this?

edit:

By printable I mean

相关标签:
5条回答
  • 2020-12-18 19:37

    I know ASCII wasn't specifically requested but this is a quick way to get a list of all the printable ASCII characters.

    for (Int32 i = 0x20; i <= 0x7e; i++)
    {
        printableChars.Add(Convert.ToChar(i));
    }
    

    See this ASCII table.

    0 讨论(0)
  • 2020-12-18 19:39

    A LINQ solution (based on Fredrik Mörk's):

    Enumerable.Range(char.MinValue, char.MaxValue).Select(c => (char)c).Where(
        c => !char.IsControl(c)).ToArray();
    
    0 讨论(0)
  • 2020-12-18 19:52

    This will give you a list with all characters that are not considered control characters:

    List<Char> printableChars = new List<char>();
    for (int i = char.MinValue; i <= char.MaxValue; i++)
    {
        char c = Convert.ToChar(i);
        if (!char.IsControl(c))
        {
            printableChars.Add(c);
        }
    }
    

    You may want to investigate the other Char.IsXxxx methods to find a combination that suits your requirements.

    0 讨论(0)
  • 2020-12-18 19:58

    Here's a LINQ version of Fredrik's solution. Note that Enumerable.Range yields an IEnumerable<int> so you have to convert to chars first. Cast<char> would have worked in 3.5SP0 I believe, but as of 3.5SP1 you have to do a "proper" conversion:

    var chars = Enumerable.Range(0, char.MaxValue+1)
                          .Select(i => (char) i)
                          .Where(c => !char.IsControl(c))
                          .ToArray();
    

    I've created the result as an array as that's what the question asked for - it's not necessarily the best idea though. It depends on the use case.

    Note that this also doesn't consider full Unicode characters, only those in the basic multilingual plane. I don't know what it returns for high/low surrogates, but it's worth at least knowing that a single char doesn't really let you represent everything :(

    0 讨论(0)
  • 2020-12-18 19:58
    public bool IsPrintableASCII(char c)
    {
         return c >= '\x20' && c <= '\x7e';
    }
    
    0 讨论(0)
提交回复
热议问题