Generating an array of letters in the alphabet

前端 未结 14 1678
粉色の甜心
粉色の甜心 2020-11-28 03:53

Is there an easy way to generate an array containing the letters of the alphabet in C#? It\'s not too hard to do it by hand, but I was wondering if there was a built in way

14条回答
  •  无人及你
    2020-11-28 04:19

    You could do something like this, based on the ascii values of the characters:

    char[26] alphabet;
    
    for(int i = 0; i <26; i++)
    {
         alphabet[i] = (char)(i+65); //65 is the offset for capital A in the ascaii table
    }
    

    (See the table here.) You are just casting from the int value of the character to the character value - but, that only works for ascii characters not different languages etc.

    EDIT: As suggested by Mehrdad in the comment to a similar solution, it's better to do this:

    alphabet[i] = (char)(i+(int)('A'));
    

    This casts the A character to it's int value and then increments based on this, so it's not hardcoded.

提交回复
热议问题