c# – 如何获得带空格和混合大小写的随机字符串?

前端之家收集整理的这篇文章主要介绍了c# – 如何获得带空格和混合大小写的随机字符串?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要生成一个包含空格和mixedCase的随机字符串.

到目前为止我已经完成了This

/// <summary>
    /// The Typing monkey generates random strings - can't be static 'cause it's a monkey.
    /// </summary>
    /// <remarks>
    /// If you wait long enough it will eventually produce Shakespeare.
    /// </remarks>
    class TypingMonkey
    {
        /// <summary>
        /// The Typing Monkey Generates a random string with the given length.
        /// </summary>
        /// <param name="size">Size of the string</param>
        /// <returns>Random string</returns>
        public string TypeAway(int size)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch;

            for (int i = 0; i < size; i++)
            {
                ch = Convert.tochar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }

            return builder.ToString();
        }
    }

我只得到没有空格的大写字符串 – 我相信调整应该非常严格,以便在汤中混合大小写和空格.

任何帮助非常感谢!

解决方法

最简单的方法是简单地创建一个包含以下值的字符串:
private readonly string legalCharacters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

然后使用RNG访问此字符串中的随机元素:

public string TypeAway(int size)
{
    StringBuilder builder = new StringBuilder();
    Random random = new Random();
    char ch;

    for (int i = 0; i < size; i++)
    {
        ch = legalCharacters[random.Next(0,legalCharacters.Length)];
        builder.Append(ch);
    }

    return builder.ToString();
}

猜你在找的C#相关文章