Generating an array of letters in the alphabet

前端 未结 14 1583
粉色の甜心
粉色の甜心 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.

    0 讨论(0)
  • 2020-11-28 04:20

    4 ways get English alphabet in Console:

    public void ShowEnglishAlphabet()
    {
        var firstLetter = 'a';
        var endLetter = 'z';
        for (var letter = firstLetter; letter <= endLetter; letter++)
        {
            Console.WriteLine($"{letter}-{letter.ToString().ToUpper()}");
        }
    }
    
    public void ShowEnglishAlphabetFromUnicodeTableDecNumber()
    {
        var firstLetter = 97;
        var endLetter = 122;
        for (var letterNumberUnicodeTable = firstLetter; 
        letterNumberUnicodeTable <= endLetter; letterNumberUnicodeTable++)
        {
            Console.WriteLine($"{(char)letterNumberUnicodeTable}- 
            {((char)letterNumberUnicodeTable).ToString().ToUpper()}");
        }
    }
    
    public void ShowEnglishAlphabetUnicodeTableEscapeSequence()
    {
        var firstLetter = '\u0061';
        var endLetter = '\u007A';
        for (var letterNumberUnicodeTable = firstLetter; 
        letterNumberUnicodeTable <= endLetter; letterNumberUnicodeTable++)
        {
            Console.WriteLine($"{letterNumberUnicodeTable}- 
            {letterNumberUnicodeTable.ToString().ToUpper()}");
        }
    }   
    
    public void ShowEnglishAlphabetUnicodeTableLinq()
    {
        var alphabets = Enumerable.Range('a', 26).Select(letter => 
        ((char)letter).ToString()).ToList();
        foreach (var letter in alphabets)
        {
            Console.WriteLine($"{letter}-{letter.ToUpper()}");
        }
    }
    
    0 讨论(0)
提交回复
热议问题