我試圖創建在C#中,在下面的方式創建的數字字母數字計數器:字母數字計數器
0001 0002 0003 ... 9999 A000 A001 ... A999 B000 ...
最後一個數字是ZZZZ。所以先是0-9,然後是A-Z。
我迷失在如何做到這一點。
我試圖創建在C#中,在下面的方式創建的數字字母數字計數器:字母數字計數器
0001 0002 0003 ... 9999 A000 A001 ... A999 B000 ...
最後一個數字是ZZZZ。所以先是0-9,然後是A-Z。
我迷失在如何做到這一點。
編輯:更新回答澄清問題。
下面的代碼將產生計數器你描述:
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);
}
更新:在您的評論後,我認爲你的問題有一個錯誤。你可能想要的僅僅是一個簡單的基礎36計數器。這裏是你可以實現的一種方式:
string base36Characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
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);
}
原來的答覆:我可能會使用產量實現它:
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");
}
}
}
9999不應該變成'999A'嗎? – jjnguy 2010-06-09 15:33:59
因爲這不是真的十六進制,你將不得不用自定義邏輯編寫自己的方法。 – 2010-06-09 15:34:14
Z999後會發生什麼?或者這很重要? – devios1 2010-06-09 15:34:19