试图在此线程[ 字母数字计数器 ] 的答案的基础上构建一个无填充的无尽(对于任何int)字母数字计数器.
我想创建一个从0开始计数的计数器.
0,1,2 ... Y,Z,10,11,12 ... 1Y,1Z,20,21 ... ZY,ZZ,100,101 ... ZZZ,1000,1001 ..无穷大(溢流). ...
计数器的目的是从我的数据库INTID 创建短URL .我想输入行的id并从中获取基数36值,我可以将其用作url.
我做了几次尝试,但他们似乎都错了.当我应该增加字符数时,我会陷入困境.即从Z到10或从ZZ到100.
我想这就是你想要的:
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
foreach (string x in EndlessBase64Sequence())
{
Console.WriteLine(x);
}
}
private static char NextBase36Char(char c)
{
if ((c >= '0' && c <= '8') ||
(c >= 'A' && c <= 'Z'))
{
return (char) (c + 1);
}
if (c == '9')
{
return 'A';
}
throw new ArgumentException();
}
public static IEnumerable<string> EndlessBase64Sequence()
{
char[] chars = { '0' };
while (true)
{
yield return new string(chars);
// Move to the next one...
bool done = false;
for (int position = chars.Length - 1; position >= 0; position--)
{
if (chars[position] == 'Z')
{
chars[position] = '0';
}
else
{
done = true;
chars[position] = NextBase36Char(chars[position]);
break;
}
}
// Need to expand?
if (!done)
{
chars = new char[chars.Length + 1];
chars[0] = '1';
for (int i = 1; i < chars.Length; i++)
{
chars[i] = '0';
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)