字母数字计数器 [英] Alphanumeric Counter

查看:134
本文介绍了字母数字计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建在C#中,在下面的方式创建的数字字母数字计数器:

I am trying to create in C# an alphanumeric counter that creates numbers in the following way:


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

最后一个数字是ZZZZ。因此,这将0-9,再AZ之后。

The last number would be ZZZZ. So it would 0-9 first, then A-Z after that.

我迷失在如何可以做到这一点。

I am lost on how this can be done.

推荐答案

编辑:更新回答澄清的问题。

Updated to answer the clarified question.

下面的代码将生成对付你描述:

The following code will generate the counter you describe:

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

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);
}

这篇关于字母数字计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆