0

I am trying to append sequential characters: A, B, ... AA, AB, ... to the beginning a a stringbuilder type. The problem I am having is that it will append all ASCII characters and not double characters. My code looks like this:

string prefix = null;
System.Text.StringBuilder text = new System.Text.StringBuilder();
for (j = 0; j < genList.Count; j++)
{
    prefix = "." + Convert.ToChart(j + 65).ToString();
    text.Append(prefix + genList[j]);
}
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
Mike
  • 2,299
  • 13
  • 49
  • 71

1 Answers1

2

What you really want is something that will output an integer in base-26, using the letters A through Z as digits. So 0 corresponds to A, 25 is Z, 26 is AA, etc.

const string digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

string ToBase26(int i)
{
    StringBuilder sb = new StringBuilder();
    do
    {
        sb.Append(digits[i % 26]);
        i /= 26;
    } while (i != 0);
    // The digits are backwards. Reverse them.
    return new string(sb.ToString.Reverse());
}

That's not the most optimum way to do it, but it'll work.

To output A, B, C, ... AA, AB, AC ... BA, etc:

for (int i = 0; i < Count; ++i)
{
    Console.WriteLine(ToBase26(i));
}
Jim Mischel
  • 131,090
  • 20
  • 188
  • 351