加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:28:48 所属栏目:百科 来源:网络整理
导读:我需要生成一个包含空格和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 eve
我需要生成一个包含空格和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();
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读