Iterating through the Alphabet - C# a-caz

后端 未结 10 1078
無奈伤痛
無奈伤痛 2020-11-29 03:03

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

10条回答
  •  -上瘾入骨i
    2020-11-29 03:49

    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.

提交回复
热议问题