Generating an array of letters in the alphabet

2019-01-07 05:01发布

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 to do this.

标签: c# alphabet
12条回答
Ridiculous、
2楼-- · 2019-01-07 05:33

C# 3.0 :

char[] az = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (Char)i).ToArray();
foreach (var c in az)
{
    Console.WriteLine(c);
}

yes it does work even if the only overload of Enumerable.Range accepts int parameters ;-)

查看更多
贼婆χ
3楼-- · 2019-01-07 05:33

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);
}
查看更多
\"骚年 ilove
4楼-- · 2019-01-07 05:34
char[] alphabet = Enumerable.Range('A', 26).Select(x => (char)x).ToArray();
查看更多
霸刀☆藐视天下
5楼-- · 2019-01-07 05:34

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;
}
查看更多
迷人小祖宗
6楼-- · 2019-01-07 05:38

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.

查看更多
我只想做你的唯一
7楼-- · 2019-01-07 05:41

I don't think there is a built in way, but I think the easiest would be

  char[] alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
查看更多
登录 后发表回答