首页 > 代码库 > 随机字符串生成函数

随机字符串生成函数

代码库

/// <summary>
/// 生成随机字符串
/// </summary>
/// <param name="length">The length.</param>
/// <param name="fixedLength">if set to <c>true</c> [fixed length].</param>
/// <param name="numberIncluded">if set to <c>true</c> [number included].</param>
/// <param name="caseSensitive">if set to <c>true</c> [case sensitive].</param>
/// <param name="additionalString">The additional string.</param>
/// <returns></returns>
public static string $GetRandomString$(int length, bool fixedLength,
 bool numberIncluded, bool caseSensitive, string additionalString)
{
        string[] randomMatrixSource = new string[]
        {
                "abcdefghijklmnopqrstuvwxyz",
                caseSensitive ? "ABCDEFGHIJKLMNOPQRSTUVWXYZ" : string.Empty,
                numberIncluded ? "0123456789" : string.Empty,
                additionalString ?? string.Empty
        };
        string randomMatrix = string.Join("", randomMatrixSource);

        int randomMatrixLength = randomMatrix.Length;
        StringBuilder randomString = new StringBuilder();
        Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
        int randomLength = length;
        if (!fixedLength)
        {
                randomLength = rand.Next(length + 1);
        }

        for (int i = 0; i < randomLength; i++)
        {
                randomString.Append(randomMatrix[rand.Next(randomMatrixLength)]);
        }

        return randomString.ToString();
}

本博客遵循CC协议2.5,即署名-非商业性使用-相同方式共享
写作很辛苦,转载请注明作者以及原文链接~
如果你喜欢我的文章,你可以订阅我的博客:-D点击订阅我的文章

  1. X﹏X 到现在还没有评论~
  1. 暂时没有trackbacks.