无尽(几乎)字母数字计数器
本文关键字:数字 计数器 几乎 无尽 | 更新日期: 2024-09-20 08:34:14
尝试在这个线程中的答案[Alphennumeric Counter]的基础上构建一个无填充的(对于任何int)字母数字计数器。
我想创建一个从0开始并像这样计数的计数器。
0,1,2…Y,Z,10,11,12…1Y,1Z,20,21…ZY,ZZ,100101…ZZZ,10001001…无穷大(溢出)。。。。
计数器的目的是从我的数据库INT
id创建短URLS。我想输入行的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';
}
}
}
}
}
这个"Base36 typefor.NET"项目看起来就像是直接插入到您需要的东西中。
这就是我目前使用的内容。
它不是无限的,但我将我的MVC3型号ID更改为long(MVC3不支持ulong),其最大值为9223372036854775807。我怀疑我的系统会有更多的行。。
private const string base36Characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static string toBase36(long x)
{
String alpha ="";
while(x>0){
alpha = base36Characters[(int) (x % 36)] + alpha;
x /= 36;
}
return alpha.ToLower();
}
测试它的数字高达zzzzz,然后我的笔记本电脑停止工作。。。