我必须使用for(char letter='A';letter<='Z'....)
。当我使用以下代码进行操作时,字母会重复大约12次。
char[] alphabet = new char[26];
for (int i = 0; i < alphabet.Length; i++)
{
for (char letter = 'A'; letter <= 'Z'; letter++)
{
alphabet[i] = letter;
Console.WriteLine(alphabet[i]);
}
}
Console.ReadKey();
答案 0 :(得分:0)
您的问题是当您只需要一个和/或和索引时,您有2个循环
var alphabet = new char[26];
var i = 0;
for (var letter = 'A'; letter <= 'Z'; letter++)
alphabet[i++] = letter;
foreach (var c in alphabet)
Console.WriteLine(c);
// or index
var alphabet = new char[26];
for (var i = 0; i < 26; i++)
alphabet[i] = (char)(i + 'A');
foreach (var c in alphabet)
Console.WriteLine(c);
// or a linq solution
var chars = Enumerable.Range('A', 26)
.Select(x => (char)x)
.ToArray();
foreach (var c in chars)
Console.WriteLine(c);
或由Fabio
提供我认为字母永远不会改变,因此您可以对其进行硬编码
var ary = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()