c# - 创建一个唯一的 5 个字符的字母数字字符串

标签 c# string alphanumeric promotion-code

我们正在考虑创建促销代码以发送给客户,我们被告知发送的每个代码必须是唯一的 - 5 个字符 - 字母数字。

我想过对连接的字符串进行哈希处理并获取哈希的前 5 个字符,但很有可能会一次又一次地出现相同的 5 个字符。

任何人都可以给我任何关于创建这个每次都是唯一的 5 字符字母数字字符串的指示吗?

最佳答案

正如我在其他回答的评论中提到的,它可能不足以满足您的目的。我编写了更多代码来生成一串随机字母数字字符。这一次,它们不限于 0-9 和 A-F——即随机生成的十六进制等价物 nibbles .相反,它们由全范围的字母数字字符组成,至少是大写字母。考虑到我们从 16 个可能的十六进制字符到 36 个可能的完整字母表和 0-9 字符,这应该足以增加唯一性的可能性。

尽管如此,当我尝试运行它超过 10,000,000 次时,仍然有很多重复项。这只是野兽的本性:你用这么短的字符串被骗的可能性相当高。无论如何,它就在这里。你可以玩弄它。如果您的客户不介意小写字母——例如如果“RORYAP”不同于“RoryAp”——那么这甚至会进一步增加唯一性的可能性。

/// <summary>
/// Instances of this class are used to geneate alpha-numeric strings.
/// </summary>
public sealed class AlphaNumericStringGenerator
{
    /// <summary>
    /// The synchronization lock.
    /// </summary>
    private object _lock = new object();

    /// <summary>
    /// The cryptographically-strong random number generator.
    /// </summary>
    private RNGCryptoServiceProvider _crypto = new RNGCryptoServiceProvider();

    /// <summary>
    /// Construct a new instance of this class.
    /// </summary>
    public AlphaNumericStringGenerator()
    {
        //Nothing to do here.
    }

    /// <summary>
    /// Return a string of the provided length comprised of only uppercase alpha-numeric characters each of which are
    /// selected randomly.
    /// </summary>
    /// <param name="ofLength">The length of the string which will be returned.</param>
    /// <returns>Return a string of the provided length comprised of only uppercase alpha-numeric characters each of which are
    /// selected randomly.</returns>
    public string GetRandomUppercaseAlphaNumericValue(int ofLength)
    {
        lock (_lock)
        {
            var builder = new StringBuilder();

            for (int i = 1; i <= ofLength; i++)
            {
                builder.Append(GetRandomUppercaseAphanumericCharacter());
            }

            return builder.ToString();
        }
    }

    /// <summary>
    /// Return a randomly-generated uppercase alpha-numeric character (A-Z or 0-9).
    /// </summary>
    /// <returns>Return a randomly-generated uppercase alpha-numeric character (A-Z or 0-9).</returns>
    private char GetRandomUppercaseAphanumericCharacter()
    {
            var possibleAlphaNumericValues =
                new char[]{'A','B','C','D','E','F','G','H','I','J','K','L',
                'M','N','O','P','Q','R','S','T','U','V','W','X','Y',
                'Z','0','1','2','3','4','5','6','7','8','9'};

            return possibleAlphaNumericValues[GetRandomInteger(0, possibleAlphaNumericValues.Length - 1)];
    }

    /// <summary>
    /// Return a random integer between a lower bound and an upper bound.
    /// </summary>
    /// <param name="lowerBound">The lower-bound of the random integer that will be returned.</param>
    /// <param name="upperBound">The upper-bound of the random integer that will be returned.</param>
    /// <returns> Return a random integer between a lower bound and an upper bound.</returns>
    private int GetRandomInteger(int lowerBound, int upperBound)
    {
        uint scale = uint.MaxValue;

        // we never want the value to exceed the maximum for a uint, 
        // so loop this until something less than max is found.
        while (scale == uint.MaxValue)
        {
            byte[] fourBytes = new byte[4];
            _crypto.GetBytes(fourBytes); // Get four random bytes.
            scale = BitConverter.ToUInt32(fourBytes, 0); // Convert that into an uint.
        }

        var scaledPercentageOfMax = (scale / (double) uint.MaxValue); // get a value which is the percentage value where scale lies between a uint's min (0) and max value.
        var range = upperBound - lowerBound;
        var scaledRange = range * scaledPercentageOfMax; // scale the range based on the percentage value
        return (int) (lowerBound + scaledRange);
    }
}

关于c# - 创建一个唯一的 5 个字符的字母数字字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36625891/

相关文章:

C# DateTime.ToString "o"格式在 Azure 上返回不同的字符串

c# - 在 Pipeline.Invoke 抛出后在 C# 中捕获 Powershell 输出

c# - 嵌套导体的屏幕未激活

C# 等效于 C++ std::string find_first_not_of 和 find_last_not_of

c# - 将一串数字加密为一串字母数字

c# - 具有自定义属性和元素名称的 XML 数组

java - 在 StringBuffer append 中对单字符值使用字符而不是 String

Java:拆分逗号分隔的字符串但忽略引号中的逗号

c++ - 从字母数字 QString 中提取数字

excel - 在 Excel 中使用结构化引用对 AlphaNumeric 进行排序