Generating an array of letters in the alphabet

前端 未结 14 1582
粉色の甜心
粉色の甜心 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 03:58
    char[] alphabet = Enumerable.Range('A', 26).Select(x => (char)x).ToArray();
    
    0 讨论(0)
  • 2020-11-28 03:58

    Assuming you mean the letters of the English alphabet...

        for ( int i = 0; i < 26; i++ )
        {
            Console.WriteLine( Convert.ToChar( i + 65 ) );
        }
        Console.WriteLine( "Press any key to continue." );
        Console.ReadKey();
    
    0 讨论(0)
  • 2020-11-28 04:00

    Surprised no one has suggested a yield solution:

    public static IEnumerable<char> Alphabet()
    {
        for (char letter = 'A'; letter <= 'Z'; letter++)
        {
            yield return letter;
        }
    }
    

    Example:

    foreach (var c in Alphabet())
    {
        Console.Write(c);
    }
    
    0 讨论(0)
  • 2020-11-28 04:01

    I wrote this to get the MS excel column code (A,B,C, ..., Z, AA, AB, ..., ZZ, AAA, AAB, ...) based on a 1-based index. (Of course, switching to zero-based is simply leaving off the column--; at the start.)

    public static String getColumnNameFromIndex(int column)
    {
        column--;
        String col = Convert.ToString((char)('A' + (column % 26)));
        while (column >= 26)
        {
            column = (column / 26) -1;
            col = Convert.ToString((char)('A' + (column % 26))) + col;
        }
        return col;
    }
    
    0 讨论(0)
  • 2020-11-28 04:02
    for (char letter = 'A'; letter <= 'Z'; letter++)
    {
         Debug.WriteLine(letter);
    }
    
    0 讨论(0)
  • 2020-11-28 04:03

    Note also, the string has a operator[] which returns a Char, and is an IEnumerable<char>, so for most purposes, you can use a string as a char[]. Hence:

    string alpha = "ABCDEFGHIJKLMNOPQRSTUVQXYZ";
    for (int i =0; i < 26; ++i)
    {  
         Console.WriteLine(alpha[i]);
    }
    
    foreach(char c in alpha)
    {  
         Console.WriteLine(c);
    }
    
    0 讨论(0)
提交回复
热议问题