我正在我的应用程序中实现 URL 缩短功能,以便为我的用户提供可在 Twitter 中使用的更短的替代 URL。重点是独立于提供相同服务的缩短服务,并将其作为我的网络应用程序的一项功能包含在内。
创建大约 6 个字符的唯一随机字符序列的最佳方法是什么?我计划将其用作我的数据库中将具有替代 URL 的项目的索引。
编辑:
此功能将用于招聘网站,其中每个新招聘广告都将获得一个自定义 URL,其中包含标题以及用于 Twitter 的较短的 URL。也就是说,独特的 6 个字符组合的总数将在很长一段时间内绰绰有余。
最佳答案
您真的需要“随机”,还是“独特”就足够了?
Unique 非常简单 - 只需将 URL 插入数据库,并将该记录的顺序 ID 转换为由您选择的字符集表示的 base-n 数字。
例如,如果您只想在序列中使用 [A-Z],您可以将记录的 ID 转换为以 26 为基数的数字,其中 A=1,B=2,... Z=26。该算法是一个递归的div26/mod26,其中商是所需的字符,余数用于计算下一个字符。
然后在检索 URL 时执行逆函数,即将 base-26 数字转换回十进制。执行 SELECT URL WHERE ID = decimal,你就完成了!
编辑:
private string alphabet = "abcdefghijklmnopqrstuvwxyz";
// or whatever you want. Include more characters
// for more combinations and shorter URLs
public string Encode(int databaseId)
{
string encodedValue = String.Empty;
while (databaseId > encodingBase)
{
int remainder;
encodedValue += alphabet[Math.DivRem(databaseId, alphabet.Length,
out remainder)-1].ToString();
databaseId = remainder;
}
return encodedValue;
}
public int Decode(string code)
{
int returnValue;
for (int thisPosition = 0; thisPosition < code.Length; thisPosition++)
{
char thisCharacter = code[thisPosition];
returnValue += alphabet.IndexOf(thisCharacter) *
Math.Pow(alphabet.Length, code.Length - thisPosition - 1);
}
return returnValue;
}
关于c# - 如何在 C# 中创建唯一的随机字符序列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1275492/