Need to loop through the letters of the alphabet.

M

moondaddy

Using c# 3.0:
I need to do a loop and for each iteration I need to call the next letter of
the alphabet. Sometimes this code may only loop 10 times, and other cases
it may loop 100 times.



I need to do something line this:



for (int i = 1; i <= X; i++)

{

Console.WriteLine(nextLetter);

}



And the result would be like this:

a

b

c

d

e

etc.



After the 26th loop the results would be like this:

aa

ab

ac

ad

ae

etc.



any ideas how I might achieve this?



Thanks.
 
M

moondaddy

I figured it out:

If anyone has a better way, please let me know. Thanks.

int i = 97; // initialize i to the char value of 'a'
string prfx = "";
int loop = 0;
int iPrfx = 97;
for (int iCnt = 0; iCnt <= 100; iCnt++)
{
loop += 1;
Console.WriteLine(prfx + Convert.ToChar(i));
i += 1;
if (loop == 26)
{
loop = 0;
prfx = Convert.ToChar(iPrfx).ToString();
iPrfx += 1;
i = 97;
}
}
 
C

Cor Ligthert[MVP]

Moondaddy,

I find this nicer

//the vars just for fun because you said C# 3.0
var x = new string[26];
for (var y = 0; y < 2; y++)
{
for (var i = 0; i < 26; i++)
{
x += Convert.ToChar(i + 97);

}
}

For others be aware this goes only for West European languages where the
alphabeth has 26 characters.

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top