如何获得带有空格和大小写混合的随机字符串? [英] How to get random string with spaces and mixed case?

查看:138
本文介绍了如何获得带有空格和大小写混合的随机字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要生成一个带有空格和MixedCase的随机字符串.

I am in need of generating a random string with spaces and mixedCase.

是我到目前为止所获得的:

This is all I got so far:

    /// <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();
        }
    }

我只得到没有空格的大写字符串-我相信该调整应该很明确,以便在汤中混合大小写和空格.

I am getting only uppercase strings with no spaces - I believe the tweak should be pretty striaghtforward to get mixed case and spaces in the soup.

任何帮助,我们将不胜感激!

Any help greatly appreciated!

推荐答案

最简单的方法是简单地创建一个具有以下值的字符串:

The easiest way to do this is to simply create a string with the following values:

private readonly string legalCharacters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

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

Then use the RNG to access a random element in this string:

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();
}

这篇关于如何获得带有空格和大小写混合的随机字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆