Alex Rivera | Logout

Iterating through the Alphabet - C# a-caz

Asked 2009-06-18T09:29:59.193
18

I have a question about iterate through the Alphabet. I would like to have a loop that begins with "a" and ends with "z". After that, the loop begins "aa" and count to "az". after that begins with "ba" up to "bz" and so on...

Anybody know some solution?

Thanks

EDIT: I forgot that I give a char "a" to the function then the function must return b. if u give "bnc" then the function must return "bnd"

Edit
Report

2 Answers

3

The following populates a list with the required strings:

List<string> result = new List<string>();
for (char ch = 'a'; ch <= 'z'; ch++){
    result.Add (ch.ToString());
}

for (char i = 'a'; i <= 'z'; i++)
{
    for (char j = 'a'; j <= 'z'; j++)
    {
        result.Add (i.ToString() + j.ToString());
    }
}
answered 2009-06-18T09:45:03.997
0

This is like displaying an int, only using base 26 in stead of base 10. Try the following algorithm to find the nth entry of the array

q = n div 26;
r = n mod 26;
s = '';
while (q > 0 || r > 0) {
  s = alphabet[r] + s;
  q = q div 26;
  r = q mod 26;
}

Of course, if you want the first n entries, this is not the most efficient solution. In this case, try something like daniel's solution.

answered 2009-06-18T09:44:33.953

Your Answer