字母数字计数器

时间:2010-06-09 15:31:19

标签: c#

我正在尝试在C#中创建一个字母数字计数器,它以下列方式创建数字:

0001
0002
0003
...
9999
A000
A001
...
A999
B000
...

最后一个号码是ZZZZ。所以它首先是0-9,然后是A-Z。

我很失落如何做到这一点。

2 个答案:

答案 0 :(得分:8)

更新:在您发表评论后,我认为您的问题存在错误。您可能想要的只是一个简单的基础36计数器。以下是实现它的一种方法:

string base36Characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

string toBase36(int x, int digits)
{
    char[] result = new char[digits];
    for (int i = digits - 1; i >= 0; --i)
    {
        result[i] = base36Characters[x % 36];
        x /= 36;
    }
    return new string(result);
}

IEnumerable<string> base36Counter()
{
    for (int n = 0; n < 36 * 36 * 36 * 36; ++n)
    {
        yield return toBase36(n, 4);
    }
}

void Run()
{
    foreach (string s in base36Counter())
        Console.WriteLine(s);
}

原始答案:我可能会使用yield实现它:

IEnumerable<string> magicCounter()
{
    // 0000, 0001, ..., 9999
    for (int i = 0; i < 10000; ++i)
    {
        yield return i.ToString("0000");
    }

    // A000, A001, ..., Z999
    for (char c = 'A'; c <= 'Z'; ++c)
    {
        for (int i = 0; i < 1000; ++i)
        {
            yield return c + i.ToString("000");
        }
    }
}

答案 1 :(得分:2)

修改:已更新,以回答澄清的问题。

以下代码将生成您描述的计数器:

<00> 0000,0001 ... 9999,A000 ... A999,B000 ... Z999,ZA00 ... ZA99,ZB00 ... ZZ99,ZZA0 ... ZZZ9,ZZZA ... ZZZZ

public const int MAX_VALUE = 38885;

public static IEnumerable<string> CustomCounter()
{
    for (int i = 0; i <= MAX_VALUE; ++i)
        yield return Format(i);
}

public static string Format(int i)
{
    if (i < 0)
        throw new Exception("Negative values not supported.");
    if (i > MAX_VALUE)
        throw new Exception("Greater than MAX_VALUE");

    return String.Format("{0}{1}{2}{3}",
                         FormatDigit(CalculateDigit(1000, ref i)),
                         FormatDigit(CalculateDigit(100, ref i)),
                         FormatDigit(CalculateDigit(10, ref i)),
                         FormatDigit(i));
}

private static int CalculateDigit(int m, ref int i)
{
    var r = i / m;
    i = i % m;
    if (r > 35)
    {
        i += (r - 35) * m;
        r = 35;
    }
    return r;
}

private static char FormatDigit(int d)
{
    return (char)(d < 10 ? '0' + d : 'A' + d - 10);
}