我正在我的应用程序中实现 URL 缩短功能,以便为我的用户提供可在 Twitter 中使用的更短的替代 URL。关键是要独立于提供相同服务的缩短服务,并将其作为我的网络应用程序的一项功能。
创建约 6 个字符的独特随机字符序列的最佳方法是什么?我计划将其用作数据库中具有备用 URL 的项目的索引。
Edited:
此功能将用于招聘网站,其中每个新招聘广告都会获得一个自定义 URL,其中包含标题以及要在 Twitter 中使用的较短 URL。也就是说,独特的 6 个字符组合的总数在很长一段时间内都足够了。
您真的需要“随机”,还是“唯一”就足够了?
Unique 非常简单 - 只需将 URL 插入数据库,然后将该记录的顺序 id 转换为由您选择的字符集表示的基数 n 数字。
例如,如果您只想在序列中使用 [A-Z],则可以将记录的 id 转换为基数 26 数字,其中 A=1、B=2、... Z=26。该算法是递归 div26/mod26,其中商是所需的字符,余数用于计算下一个字符。
然后,在检索 URL 时,执行逆函数,即将 26 进制数转换回十进制。执行 SELECT URL WHERE ID =decimal,就完成了!
EDIT:
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)